2
votes

I'm trying to send json data over post request but getting errors, I've tried many answers of stackoverflow but not getting answer I've also tried jsonp method but not getting any thing.

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

angular.js:14516 Possibly unhandled rejection: {"data":null,"status":-1,"config":{"method":"POST","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","url":"http://localhost:3000/lvl/2/data","headers":{"Authorization":"Basic dGVzdDp0ZXN0","Content-Type":"application/x-www-form-urlencoded","Accept":"application/json, text/plain, /"},"data":{"Code":"test data"}},"statusText":""}

http post request:

$http({
    url:'http://localhost:3000/lvl/2/data',
    method:"POST",
    headers: {
        'Authorization': 'Basic dGVzdDp0ZXN0',
        'Content-Type': 'application/x-www-form-urlencoded'
    },
    data: {
        'Code': 'test data'
    }
}).then(function() {
    console.log('submitted')
});

NodeJs Post request:

router.post('/lvl/2/data', function (req, res){
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
    res.header("Access-Control-Max-Age", "3600");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    console.log(req.body);
    res.send('submitted');
});
1
does your nodejs handle OPTIONS preflight request correctly? - Jaromanda X
although Origin 'null' suggests the page that is making the request is loaded using file:// protocol - Jaromanda X
your server isnt work like you doing - Enrique YC
yes page is loaded using file:// protocol - Jatin
see this Response to preflight request doesn't pass access control check - that's the OPTIONS preflight that is failing - read about CORS preflight to understand - if you were using express on the server, you'd use express-cors - npmjs.com/package/express-cors - Jaromanda X

1 Answers

0
votes

You can temporary disable checking CORS with extension for browser:

Chrome:

Allow-Control-Allow-Origin: *

For Opera you should install:

1)Extension allows you to install extensions from Chrome Web Store

2)Allow-Control-Allow-Origin: *