代码之家  ›  专栏  ›  技术社区  ›  James L.

ExpressJs应用程序中的cors js正在阻止应通过的请求

  •  0
  • James L.  · 技术社区  · 6 年前

    我相信我正在设置我的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 “起源” http://localhost:3000

    你知道这里失败的是什么吗?我非常需要回应 no-cors 对我不起作用。

    2 回复  |  直到 6 年前
        1
  •  1
  •   James L.    6 年前

    原点只是一个字符串,不是正则表达式。正则表达式的定义必须如下所示: origin: [/.*localhost.*/]

        2
  •  0
  •   shili.oussama    6 年前

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

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