首页 文章

ExpressJs应用程序中的cors-js阻止了应该通过的请求

提问于
浏览
0

我相信我正在设置我的快递应用程序的CORS设置,但我的请求仍然失败 .

Express Cors设置:

app.use(
  cors({
    origin: ["localhost"]
  })
); 
app.options("*", cors()); // include before other routes

也试过了

app.use(
  cors()
); 
app.options("*", cors()); // include before other routes

请求:

fetch(`localhost:5000/charge`, {
                method: "POST",
                headers: {
                    "Content-Type": "application/json"
                },
                body: (
                    JSON.stringify({
                        stripeToken: token.id,
                        chargeAmount: Math.round(100 * this.state.donationAmount) // Needs to be an integer in cents
                    })
                )
            })
                .then(res => {
                    return res.text();
                })
                .then(txt => {
                    console.log(txt);
                })

浏览器错误:

访问'http://localhost:5000/charge ' from origin ' http://localhost:3000 ' has been blocked by CORS policy: No ' Access-Control-Allow-Origin ' header is present on the requested resource. If an opaque response serves your needs, set the request' s模式获取'no-cors'以获取禁用CORS的资源 .

知道这里失败的是什么吗?我需要回复所以 no-cors 对我不起作用 .

2 回答

  • 0

    尝试添加前端的完整网址,并添加如下方法:

    app.use(cors({
        origin: ['http://localhost:5000'],
        methods: ['GET', 'POST', 'PUT', 'DELETE'],
        credentials: true // enable set cookie
    }));
    
  • 0

    原点只是一个字符串,而不是RegEx . RegEx必须定义如下: origin: [/.*localhost.*/]

相关问题