办法有很多这里只列举两例 (批改 nextconfig 文件和应用 express+http 中间件)
跨域解决问题
本地开发 dev 环境
1、next.config.js 文件 重写地址 (实现跨域)
module.exports = {async rewrites() {
return [
// 接口申请 前缀带上 /api-text/
{source: '/api-text/:path*', destination: `http://127.0.0.1:8080/:path*`},
]
},
}
2、express http-proxy-middleware 中间件解决
-
根目录下创立 server.js 文件
// server.js const express = require('express') const next = require('next') const {createProxyMiddleware} = require('http-proxy-middleware') const devProxy = { '/api-text': { target: 'http://127.0.0.1:8080/', // 端口本人配置适合的 pathRewrite: {'^/api-text': '/'}, changeOrigin: true }, '/api': { target: 'http://127.0.0.1:3000/', // 端口本人配置适合的 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) })
- 批改 package.json,增加一则内容
"scripts": {"dev:node-middleware": "node server.js",},