简体   繁体   中英

Error “No 'Access-Control-Allow-Origin' header is present on the requested resource” even after setting headers on server and client

I have a NodeJS/Express backend API server running on port 8002 and a ReactJS frontEnd app on port 3000.

I am submitting a form from the reactJS frontend app to post on the API server which saves it to a database.

I call a function saveAndContinue to submit the form.

Below is the snippet that does that :

class Confirmation extends Component{
saveAndContinue = (e) => {
    e.preventDefault();

    console.log("props : " + JSON.stringify(this.props.values));
    var form_id = Math.floor(Math.random() * 1000000); 
    let headers = new Headers();

      headers.append('Content-Type', 'application/json');
      headers.append('Accept', 'application/json');

      headers.append('Access-Control-Allow-Origin', '*');

    fetch("http://localhost:8002/sharepoint/big_data_poc/" + form_id,{
        method:'POST',
        //mode: 'cors',
        body:JSON.stringify(this.props.values),
        headers: headers
    }).then(res => res.json()).then(this.setState({confirmation_id:form_id}))
    .then(response => console.log('Success:', JSON.stringify(response)))
    .catch(error => console.error('Error:', error));
    this.props.nextStep();
}

Also I added the Access-Control-Allow-Origin to the nodeJS server response header

cb_service.prototype.addForm = function(req,res,form_id, doc_type,payload){
logger.info(JSON.stringify(payload));
bucket.upsert(form_id,payload,function(err,result){
    if(err){
        logger.error("error inserting data in couchbase")
    }
    else {
        res.setHeader('Access-Control-Allow-Origin','*')
        res.setHeader('Access-Control-Allow-Methods','POST, GET, OPTIONS, PUT')
        res.setHeader('mode','cors')
        logger.info("successful inserts");
        res.status(200);

        return res.json({"success":"ok"});       
    }
 })
}

I don't see any request coming into the server at all. I just see the below error in the browser console :

Failed to load http://localhost:8002/sharepoint/big_data_poc/944960 : 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Any help is most appreciated!! I think I have done everything that's recommended by the similar questions on SO. Even Safari throws the below error :

[Error] Failed to load resource: Origin http://localhost:3000 is not allowed by Access-Control-Allow-Origin. (408661, line 0)

[Error] Fetch API cannot load http://localhost:8002/sharepoint/big_data_poc/408661 . Origin http://localhost:3000 is not allowed by Access-Control-Allow-Origin.

Thanks so much!

install cors and you wont be any problems const cors = require('cors'); app.use(cors()); const cors = require('cors'); app.use(cors()); link on npm https://www.npmjs.com/package/cors

Try to add those middleware to your app

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

// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8888');

// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
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