I am using fetch api to make request from reactjs to node.js backend with Basic Authorization with the code below...
React
fetch(baseUrl, {
method: 'get',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
authorization: 'Basic ' + secret,
},
}).then((res) => {
if (res.ok) {
return res.json();
} else {
return Promise.reject(res.statusText);
}
})
.then((resBody) => {
//
})
.catch((error) => {
console.error(error);
});
Node.js
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Authorization');
res.setHeader('Access-Control-Allow-Credentials', true);
return next();
});
app.use((req, res, next) => {
const base64Credentials = (req.headers.authorization || '').split(' ')[1] || '';
const [username, password] = Buffer.from(base64Credentials, 'base64').toString().split(':');
const auth = { username: 'username', password: '123456' }
console.log(username, password, auth.username, auth.password);
// comment below
if (username === auth.username && password === auth.password) {
return next();
} else {
res.status(401).send('Authentication required.'); // custom message
}
});
The following error is occur when I try to make the request.
Access to fetch at 'http://127.0.0.1:5000/' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
However, when I comment the comparison part in the second middleware if (username === auth.username && password === auth.password) it works fine. I have tried using Postman to send request it also no problem happen. The problem only occur when I make the request from react app. Anyone know what is the reason? Thanks a lot