【问题标题】:'Access-Control-Allow-Credentials' header in the response is ' ' which must be 'true' when the request's credentials mode is 'include' [duplicate]响应中的“Access-Control-Allow-Credentials”标头为“”,当请求的凭据模式为“包含”时,该标头必须为“真”[重复]
【发布时间】:2021-04-17 09:15:36
【问题描述】:

我在制作MMORPG项目的过程中学习服务器-客户端通信。

*更新:服务器端代码已编辑。

这是服务器端代码。

router.post('/login', async (request, response, next) => {
  passport.authenticate('login', async (error, user) => {
    try {
      if (error) {
        return next(error);
      }
      if (!user) {
        return next(new Error('email and password are required'));
      }
      request.logIn(user, { session: false }, (err) => {
        if (err) {.....
  

这是客户端代码

function postData(url, data = {}) {
  return fetch(url, {
    method: 'POST',
    mode: 'cors',
    cache: 'no-cache',
    credentials: 'include',
    headers: {
      'Content-Type': 'application/json',
    },
    redirect: 'follow',
    body: JSON.stringify(data),
  }).then((response) => response.json());
}

login() {
    const loginValue = this.loginInpout.value;
    const passwordValue = this.passwordInput.value;

    postData('http://localhost:4000/login', { email: loginValue, password: passwordValue })
      .then((response) => {
        if (response.status === 200) {
          this.startScene('Game');
        } else {
          console.log(response.message);
          window.alert('invald username or password');
        }
      }).catch((error) => {
        console.log(error.message);
        window.alert('invald username or password');
      });
    }

调用 login() 函数时,fetch() 函数在浏览器控制台中抛出此消息。 (http://localhost:4000/login) 是服务器端,(http://localhost:8000) 是客户端。

Access to fetch at 'http://localhost:4000/login' from origin 'http://localhost:8000' 
has been blocked by CORS policy: Response to preflight request doesn't pass access 
control check: The value of the 'Access-Control-Allow-Credentials' header in the 
response is '' which must be 'true' when the request's credentials mode is 'include'.

LoginScene.js:48 POST http://localhost:4000/login net::ERR_FAILED

Failed to fetch  <<-- fetch error message on browser console

我尝试了很多不同的方法来修复它,但没有好的结果。

【问题讨论】:

    标签: javascript express cors


    【解决方案1】:

    试试下面的代码:

    import express from "express";
    import http from "http";
    
    const app = express();
    const server = http.createServer(app);
    
    const sio = require("socket.io")(server, {
        handlePreflightRequest: (req, res) => {
            const headers = {
                "Access-Control-Allow-Headers": "Content-Type, Authorization",
                "Access-Control-Allow-Origin": req.headers.origin, 
                "Access-Control-Allow-Credentials": true
            };
            res.writeHead(200, headers);
            res.end();
        }
    });
    
    sio.on("connection", () => {
        console.log("Connected!");
    });
    

    【讨论】:

    • 我在使用 socket.io 时误导了你。它与 socket.io 无关。 fetch() 函数抛出错误。
    猜你喜欢
    • 2018-01-13
    • 2019-02-08
    • 2017-10-02
    • 2022-11-28
    • 2018-12-24
    • 2018-07-31
    • 2018-12-16
    • 2021-04-04
    相关资源
    最近更新 更多