提问者:小点点

无法在Fetch Get请求中设置任何标头


Im正在尝试从浏览器发送get请求到我的后端(node+express)。但不知何故我的头部似乎没有设置好。

前面是这样的:

let accessToken = localStorage.getItem('accessToken');

    fetch('http://localhost:3000/checkLogin', {
        method: 'GET',
        mode: same-origin,

        withCredentials: true,
        credentials: 'include',
        headers: {
            'Authorization': 'Bearer ' + accessToken,
            'Content-Type': 'text/plain',
            'X-Test':'test'
        }
    })
    .then(data => {
        console.log('Success:', data);
    })
    .catch((error) => {
        console.error('Error:', error);
    });

在后端,我尝试启用自定义头:

server.use(function(req, res, next) {
console.log("CORS");
res.set('Access-Control-Allow-Origin', 'localhost:3000/testLogin');
res.set('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.set('Access-Control-Allow-Headers', 'Authorization, Content-Type, X-Test');
next();});

我已经试过类似问题的答案,但没有一个奏效。

当我打印服务器收到的报头时,我得到:

host: 'localhost:3000',
  connection: 'keep-alive',
  'cache-control': 'max-age=0',
  'sec-ch-ua': '"Google Chrome";v="89", "Chromium";v="89", ";Not A Brand";v="99"',
  'sec-ch-ua-mobile': '?0',
  'upgrade-insecure-requests': '1',
  'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36',
  accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
  'sec-fetch-site': 'same-origin',
  'sec-fetch-mode': 'navigate',
  'sec-fetch-user': '?1',
  'sec-fetch-dest': 'document',
  referer: 'http://localhost:3000/',
  'accept-encoding': 'gzip, deflate, br',
  'accept-language': 'de-DE,de;q=0.9,en-US;q=0.8,en;q=0.7'


共1个答案

匿名用户

您指定的原点无效。它需要有一个方案(例如http://https:/)。还要注意,起源没有路径。因此,例如,'localhost:3000/testlogin',而不是'http://localhost:3000':

res.set('Access-Control-Allow-Origin', 'http://localhost:3000');