最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to use proxy in package.json in next.js? - Stack Overflow

programmeradmin3浏览0评论

In create-react-app(s) it is possible to specify a proxy in the package.json like this:

{
    "name": "client",
    "version": "0.1.0",
    "private": true,
>>> "proxy": "http://localhost:5000", <<<
    "dependencies": {
            ...
    },
    "scripts": {
            ...
    },
    "eslintConfig": {
            ...
    },
    "browserslist": {
        "production": [
            ...
        ],
        "development": [
            ...
        ]
    }
}

Doing the same in a next.js app has no effect whatsoever. Is there a workaround? This would be especially useful when starting to demission an old front-end but still using the backend.

In create-react-app(s) it is possible to specify a proxy in the package.json like this:

{
    "name": "client",
    "version": "0.1.0",
    "private": true,
>>> "proxy": "http://localhost:5000", <<<
    "dependencies": {
            ...
    },
    "scripts": {
            ...
    },
    "eslintConfig": {
            ...
    },
    "browserslist": {
        "production": [
            ...
        ],
        "development": [
            ...
        ]
    }
}

Doing the same in a next.js app has no effect whatsoever. Is there a workaround? This would be especially useful when starting to demission an old front-end but still using the backend.

Share asked May 14, 2020 at 7:37 Fabian BoslerFabian Bosler 2,5102 gold badges33 silver badges60 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 2

Try to use this package from npm to create a Node.js proxy for Express: http-proxy-middleware

Then You can configure the target option to proxy requests to the correct domain:

const proxy = require('http-proxy-middleware')

app.use('/api', proxy({ target: 'http://localhost:5000', changeOrigin: true }));

Find similar package for next.js here: next-http-proxy-middleware

Another way is to use rewrites config: https://nextjs/docs/api-reference/next.config.js/rewrites

module.exports = {
    async rewrites() {
        return [
            {
                source: '/api/:slug*',
                destination: 'http://www.example./api/:slug*'
            },
        ]
    },
}
发布评论

评论列表(0)

  1. 暂无评论