自己已经解决,答案在最后哟
用了官方的server.js
/* eslint-disable no-console */
const express = require('express')
const next = require('next')
const devProxy = {
'/api': {
target: 'http://localhost:7001/',
pathRewrite: { '^/api': '/' },
changeOrigin: true
}
}
const port = parseInt(process.env.PORT, 10) || 3000
const env = process.env.NODE_ENV
const dev = env !== 'production'
const app = next({
dir: '.', // base directory where everything is, could move to src later
dev
})
const handle = app.getRequestHandler()
let server
app
.prepare()
.then(() => {
server = express()
// Set up the proxy.
if (dev && devProxy) {
const proxyMiddleware = require('http-proxy-middleware')
Object.keys(devProxy).forEach(function (context) {
server.use(proxyMiddleware(context, devProxy[context]))
})
}
// Default catch-all handler to allow Next.js to handle all other routes
server.all('*', (req, res) => handle(req, res))
server.listen(port, err => {
if (err) {
throw err
}
console.log(`> Ready on port http://localhost:${port} [${env}]`)
})
})
.catch(err => {
console.log('An error occurred, unable to start the server')
console.log(err)
})
封装的axios都是使用的/api请求
let request = axios.create({
baseURL: process.env.NODE_ENV === "production" ? "/api" : "/api"
});
到底是哪里的问题呢
答:这一段的判断去掉就好,因为部署到线上也需要配置代理。
顺便放下我的博客:nextjs重构的react http://www.qqjishu.net/
//if (dev && devProxy) {
const proxyMiddleware = require('http-proxy-middleware')
Object.keys(devProxy).forEach(function (context) {
server.use(proxyMiddleware(context, devProxy[context]))
})
// }