【问题标题】:NextJS custom server gives CORS error after build with 'npm run build'NextJS 自定义服务器在使用“npm run build”构建后出现 CORS 错误
【发布时间】:2021-08-08 19:40:16
【问题描述】:

这工作正常。我使用 npm run dev 来启动这个自定义服务器(server.js 代码如下)。我需要使用服务器端渲染进行生产构建,并且无法使用下一个导出

在我运行 npm run build 后,身份验证不起作用。我发现后端服务器没有收到 cookie。所以我在 axios 请求中添加了withCredentials: true。但随后所有请求都被 cors 政策 阻止。错误信息是,

跨源请求被阻止:同源策略不允许读取位于“http://localhost:5002/api/v1/users/authenticate”的远程资源。 (原因:如果 CORS 标头“Access-Control-Allow-Origin”为“*”,则不支持凭据。

我在我的 backend nodejs express server 中使用 cors 包。

我尝试了所有互联网解决方案。允许客户端和服务器上的 cors 来源,使用 cors 选项将 localhost 作为来源。但没有一个有效。

这里是nextjs自定义服务器代码,

const express = require('express');
const next = require('next');
const { createProxyMiddleware } = require('http-proxy-middleware');

const port = 3000;
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();

const apiPaths = {
  '/api': {
    target: 'http://localhost:5002',
    pathRewrite: {
      '^/api': '/api',
    },
    changeOrigin: true,
  },
};

const isDevelopment = process.env.NODE_ENV !== 'production';

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

    if (isDevelopment) {
      server.use('/api', createProxyMiddleware(apiPaths['/api']));
    }

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

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

Axios 的客户端代码,

        const token = localStorage.getItem('token');

        if (token) {

          const data = await axios({
            method: 'post',
            url: `${process.env.NEXT_PUBLIC_API}/api/v1/users/authenticate`,

            withCredentials: true,
            data: { token },
          });

【问题讨论】:

  • 能否在后端添加配置CORS的代码?
  • @ĐăngKhoaĐinh //启用代理 app.enable('trust-proxy'); //cors app.use('/api/', cors()); app.options('*', cors());这是我的后端 cors。

标签: node.js build axios cors next.js


【解决方案1】:

如果你查看错误

同源策略不允许读取远程资源 'http://localhost:5002/api/v1/users/authenticate'。 (原因:凭证 如果 CORS 标头“Access-Control-Allow-Origin”为 ‘*’)。

它说的是:当你在请求withCredentials: true,中包含凭证时,来源不能是“*”,这是使用cors())时的默认选项。您可以在 cors 选项中指定请求的来源。您还需要添加“凭据”选项来传递标头。

const corsOptions = {
       origin : "YOUR_FRONTEND", // the origin of the requests - frontend address
       credentials : true  
}

然后:

app.use('/api/', cors(corsOptions)); 
app.options('*', cors(corsOptions));

【讨论】:

    【解决方案2】:

    您需要将 cors 库添加到您的 Express API。它允许您从 API 运行 cors 请求。

    安装cors,然后使用添加中间件

    const cors = require("cors");
    app.use(cors())
    

    您的 CORS 规则可以自定义。使用上面的代码,您基本上允许来自任何来源的所有 CORS 请求。

    【讨论】:

    • 已经在使用 cors。但我发现了问题,我使用的是来自 process.env 的后端 api 链接localhost:5002/api/v1。当我在 axios 中使用相对 url 时,它可以工作。但是现在,如何像开发服务器一样将下一个生产构建代理到后端?
    猜你喜欢
    • 2021-08-10
    • 2021-03-03
    • 2019-07-20
    • 2021-11-16
    • 2021-09-02
    • 1970-01-01
    • 2018-04-30
    • 2021-05-28
    • 2022-01-23
    相关资源
    最近更新 更多