Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

CORS PUT: Not found with jQuery.ajax

CORS PUT: Not found with jQuery.ajax

Problem

I want to send some raw data to a subdomain of mine:

$.ajax({
    url: "http://accounts.example.com:3000/me",
    type: "PUT",
    data: { wabo: "chabo" },
    dataType: "json",
    xhrFields: {
        withCredentials: true
    }
});

The browser now sends two requests:

  1. OPTIONS to accounts.example.com:3000/me to check if CORS headers are valid
  2. PUT to send data

The first one fails with HTTP 404 Not Found. The CORS repsonse header looks valid:

HTTP/1.1 404 Not Found
X-Powered-By: Express
Access-Control-Allow-Origin: http://node.example.com:3000
Access-Control-Allow-Methods: HEAD, GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Headers: Content-Type, X-Requested-With, Origin, Accept
Access-Control-Allow-Credentials: true
Content-Type: text/plain
Set-Cookie: connect.sid=s%3Aru8njoU2ZAnoKL2W2w%2B0BHF7.%2Fe%2FQI5f6NKRWQvWlcYEkMG7HHSxxj0haFDBUID2g45A; Domain=.example.com; Path=/
Date: Sun, 04 Nov 2012 11:31:22 GMT
Connection: keep-alive
Transfer-Encoding: chunked

In app.js of my node environment I have:

app.all('*', function(req, res, next) {
    res.header('Access-Control-Allow-Origin', 'http://node.example.com:3000');
    res.header('Access-Control-Allow-Methods', 'HEAD, GET, POST, PUT, DELETE, OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Content-Type, X-Requested-With, Origin, Accept');
    res.header('Access-Control-Allow-Credentials', 'true');
    next();
});

and

var me = require('./me');
app.get('/me', loadUser, me.show);
app.put('/me', loadUser, me.update);

GETting data from the subdomain is no problem only sending Any idea what I have forgotten?

Regards, bodo

Problem courtesy of: bodokaiser

Solution

Try this instead:

app.all('*', function(req, res, next) {
    res.header('Access-Control-Allow-Origin', 'http://node.example.com:3000');
    res.header('Access-Control-Allow-Methods', 'HEAD, GET, POST, PUT, DELETE, OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Content-Type, X-Requested-With, Origin, Accept');
    res.header('Access-Control-Allow-Credentials', 'true');

    if( req.method.toLowerCase() === "options" ) {
        res.send( 200 );
    }
    else {
        next();
    }
});
Solution courtesy of: Esailija

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

CORS PUT: Not found with jQuery.ajax

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×