【nextjs dev解决跨域问题】

1、安装插件 yarn add express http-proxy-middleware
2、根目录下方添加文件 server.js : 内容如下

// server.js
const express = require('express')
const next = require('next')
const  { createProxyMiddleware }  = require('http-proxy-middleware')
const devConfig = require('./devConfig')

const devProxy = {
    '/api': {
        target: devConfig.proxyUrl, // 端口自己配置合适的
        pathRewrite: {
            '^/api': '/'
        },
        changeOrigin: true
    }
}

const port = parseInt(process.env.PORT, 10) || 3000
const dev = process.env.NODE_ENV !== 'production'
const app = next({
    dev
})
const handle = app.getRequestHandler()

app.prepare()
    .then(() => {
        const server = express()

        if (dev && devProxy) {
            Object.keys(devProxy).forEach(function(context) {
                server.use(createProxyMiddleware(context, devProxy[context]))
            })
        }

        server.all('*', (req, res) => {
            handle(req, res)
        })

        server.listen(port, err => {
            if (err) {
                throw err
            }
            console.log(`> Ready on http://localhost:${port}`)
        })
    })
    .catch(err => {
        console.log(err)
    })

3、修改package.json 文件的scripts dev配置

    "dev": "node server.js",

你可能感兴趣的:(share,前端,node.js)