1

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

2
  • do you use the CORD npm? Commented Dec 5, 2020 at 14:31
  • I didn't use cors. Commented Dec 5, 2020 at 14:42

1 Answer 1

1

it seems that the CORS npm is no installed npm i cors and write this code:

var express = require('express')
var cors = require('cors')
var app = express()
 
app.use(cors())

more information about CORS npm

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.