【问题标题】:CORS error not showing when using express [duplicate]使用 express 时未显示 CORS 错误 [重复]
【发布时间】:2020-07-31 02:41:37
【问题描述】:

当我使用带有 http 的 Nodejs 创建两台服务器并且都将 express 作为请求处理程序时,其中一台在 localhost:3000 运行,用于处理 api。另一个在 localhost:5000,我尝试从 localhost:3000 获取 api,我希望得到一个 cors 错误,但令人惊讶的是我可以毫无错误地获取它。不知道为什么,是因为快递吗?

localhost:5000 代码

const express = require('express');
const app = express();

const axios = require('axios');

const http = require('http');
const server = http.createServer(app);

app.get('/', async (req, res) => {
 try {
    const response = await axios.get('http://localhost:3000/users');
    console.log(typeof response.data);
    res.send(response.data[1]);
} catch(err) {
    console.error(err);
  }
});

server.listen(5000);

【问题讨论】:

  • 我不确定我是否理解 - 你没有提出 XHR 请求。
  • 他们在同一台机器上。
  • 您已经创建了一个代理服务器,您没有发出和 CORS 请求。当用户使用 somedomain.biz 并且站点尝试向 someotherdomain.org 发出请求时,就会发生 CORS 请求。这是纯粹发生在客户端的事情。

标签: node.js express cors


【解决方案1】:

尝试制定 cors 规则,

app.use(function (req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');
    res.setHeader('Access-Control-Allow-Methods', 'GET,HEAD,PUT,PATCH,POST,DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With');
    res.setHeader('Access-Control-Allow-Credentials', true);
    next();
  });

【讨论】:

    猜你喜欢
    • 2015-11-21
    • 2019-08-26
    • 2021-03-07
    • 2023-02-25
    • 1970-01-01
    • 2019-11-09
    • 1970-01-01
    • 2021-04-29
    • 1970-01-01
    相关资源
    最近更新 更多