0

In my node.js, express.js application I am trying to post json data to http://localhost:3000/api/delivered. The HTML file-

<html>
<body>
<input type="submit" value="submit" id="delivered"/>
</body>

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js" </script>
<script type="text/javascript">

$('#delivered').on('click', function () {
        var id = {"_id": "123"};

        $.ajax({
            type: 'POST',
            url: 'http://localhost:3000/api/delivered',
            contentType: 'application/json',
            data : JSON.stringify(id),
            dataType: "json",
            success: function () {
                console.log('Delivered');
            },
            error: function () {
                alert('Error occured while entering');
            }
        });

    });

I am getting the error-

XMLHttpRequest cannot load http://localhost:3000/api/delivered. 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.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Rahul Chawla
  • 190
  • 1
  • 3
  • 14
  • The domain you're calling does not support CORS, so you're being blocked by the [Same Origin Policy](http://en.wikipedia.org/wiki/Same-origin_policy). Assuming you have control of the domain you need to enable CORS headers on the server. If you don't have control of the server then you will have to use one of the workarounds listed in the question I marked as duplicate. – Rory McCrossan Jun 24 '16 at 19:13
  • I checked a few solutions but they weren't working out for me. That's why I posted my specific code. Thanks anyway, I'll check the question you marked duplicate. – Rahul Chawla Jun 24 '16 at 19:43

1 Answers1

0

Try adding the following middleware to your NodeJS/Express app

    // Add headers
    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();
    });

Another way is as below :

var cors = require('cors');

// use it before all route definitions
app.use(cors({origin: 'http://localhost:8888'}));
Tanvi B
  • 1,577
  • 11
  • 14
  • My central `app.js` and `api.js(for routing definitions)` are as follows http://pastebin.com/ixHSQ5Bv http://pastebin.com/jRVRPvCS I have made the changes still same error. Can you check if I have done it correctly, it will be very helpful. – Rahul Chawla Jun 24 '16 at 19:36