当前位置: 首页 > 知识库问答 >
问题:

当请求的凭据模式为包含[重复]时,响应中的访问控制允许凭据标头必须为true。

阙博容
2023-03-14

在制作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()函数时,finch()函数将此消息抛出到浏览器控制台。(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

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

共有1个答案

况博容
2023-03-14

请尝试以下代码:

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!");
});
 类似资料: