skip to Main Content

I am creating a signup page using React and for my Backend I am using Node JS. When I am trying to call my signup api of Backend I am getting the following error
api.js:31 Refused to connect to ‘http://localhost:3001/user/signup’ because it violates the document’s Content Security Policy.
I am using the following sample function just to firstly connect to the backend api and then I will integrate the real form data.

export const postAPIWithoutHeader = async () => {
    console.log("postAPIWithoutHeader")
    console.log(body)
  try {
    var myHeaders = new Headers();
    myHeaders.append("Content-Type", "application/json");

     var raw = JSON.stringify({
    "name": "some",
    "email": "[email protected]",
    "password": "Password234@",
    "role": "1",
    "require_servie": true
    });

    var requestOptions = {
    method: 'POST',
    headers: myHeaders,
    body: raw,
    redirect: 'follow'
    };

    let res = fetch("http://localhost:3001/user/signup", requestOptions)
      .then(response => response.text())
      .then(result => console.log(result))
      .catch(error => console.log('error', error));
    
    // console.log(reqBod)
    console.log("res",res)
    return res.data
  } catch (err) {

    console.log("the error we get is ",err);
    return err
  }
}

on my node backend I have allowed the cors using the following code in my app.js of backend

const corsOptions ={
    origin:['http://localhost:3000','http://localhost:3003'], 
    credentials:true,
    methods:"POST, GET, OPTIONS",
    optionSuccessStatus:200
};


app.use(cors(corsOptions))
app.options('*', cors(corsOptions));

I have tested the ap using postman and it works ok with the same URL.
Any help would be really appreciated

I was expecting to get the response from backend api.

2

Answers


  1. Chosen as BEST ANSWER

    So after spending 2 days on this issue I found out that the only thing I had to do add http://localhost:3001; in my connect-src of meta tag of index.html file and it worked for me connect-src 'self' www.googletagmanager.com http://localhost:3001;


  2. Try the below configuration to whitelist the domains

    app.use((req, res, next) => {
      const allowedOrigins = ['http://localhost:3000','http://localhost:3003'];
      const origin = req.headers.origin;
      if (allowedOrigins.includes(origin)) {
           res.setHeader('Access-Control-Allow-Origin', origin);
      }
      res.header('Access-Control-Allow-Methods', 'GET, OPTIONS'); // add all the methods you want to add
      res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
      res.header('Access-Control-Allow-Credentials', true);
      return next();
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search