Im trying to send a get Request from the browser to my backend (node + express). But somehow my headers dont seem to get set.
Heres the Frontend:
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); });
In the backend i tried to enable custom headers:
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();});
I already tried the answers of similar questions but none of them worked.
when i print the headers received by the server i get:
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'
Answer
The origin you’re specifying is invalid. It needs to have a scheme (e.g., http://
or https://
). Also note that origins don’t have paths. So for instance, instead of 'localhost:3000/testLogin'
, it would be 'http://localhost:3000'
:
res.set('Access-Control-Allow-Origin', 'http://localhost:3000');