方法有很多这里只列举两例(修改nextconfig文件和使用express+http中间件、api-cors)
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
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)
})
"scripts": {
"dev:node-middleware": "node server.js",
},
3、 使用cors中间件(这是官方的例子)
// Helper method to wait for a middleware to execute before continuing
// And to throw an error when an error happens in a middleware
export default function initMiddleware(middleware) {
return (req, res) =>
new Promise((resolve, reject) => {
middleware(req, res, (result) => {
if (result instanceof Error) {
return reject(result)
}
return resolve(result)
})
})
}
import Cors from 'cors'
import initMiddleware from '../../lib/init-middleware'
// Initialize the cors middleware
const cors = initMiddleware(
// You can read more about the available options here: https://github.com/expressjs/cors#configuration-options
Cors({
// Only allow requests with GET, POST and OPTIONS
methods: ['GET', 'POST', 'OPTIONS'],
})
)
export default async function handler(req, res) {
// Run cors
await cors(req, res)
// Rest of the API logic
res.json({ message: 'Hello Everyone!' })
}