简体   繁体   中英

couldn't make node api call from react app

I am making a api call from react app running on port 3000 to node api running on port 8080.And i am getting error as:

XMLHttpRequest cannot load http://localhost:8080/register . Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ' http://localhost:3000 ' is therefore not allowed access.

My react api call is:

export const addUser=(data) =>{
console.log(data);
return function(dispatch,data){
axios.post('http://localhost:8080/register',{
    phone:data.phone,
    password:data.password,
    first_name:data.fname,
    last_name:data.lname,
    dob:data.dob,
    gender:data.gender
})
.then(response =>{
  console.log('data submitted successfully');
  dispatch({
    type : AddUser,
    User : data
  })
}).catch(err =>{
  console.log(err);
})
}
}

And my server side code is in node.js and i included the headers as:

app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', "*");
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
});

I still can't post my data to my database.. Any suggestion will really help me. Thanks.

Option 1:

npm install cors


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

Option 2: Or Use setHeader Method instead of only header

app.use(function (req, res, next) {


    res.setHeader('Access-Control-Allow-Origin', '*');


    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

    res.setHeader('Access-Control-Allow-Credentials', true);

    // Pass to next layer of middleware
    next();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM