This is my ajax post request. I am using nodejs and mongodb.When I post a request I get an error stating CANNOT POST.currlocation in the POST request is the json object. I have also tried to remove the content-type from POST request and tried to send the data as JSON.stringify(currlocation),it still doesnt work
$.ajax({
type: "POST",
url: "http://myurl.rhcloud.com",
contentType: "application/json",
data: currLocation,
dataType: "text",
success: function( response ){
console.log(response);
},
error: function( error ){
console.log( "ERROR:", error );
}
});
I am using nodejs and mongodb. My configuration in server.js file is
self.app.configure(function () {
self.app.use(express.bodyParser());
self.app.use(express.favicon());
self.app.use(express.json());
self.app.use(express.urlencoded());
self.app.use(express.methodOverride());
self.app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
My post request in server.js file is
self.app.post('/', self.routes['post'] );
self.routes['post'] = function(req, res){
console.log("inside post");
var mongojs = require('mongojs');
var dbName = "/favloc";
var connection_string = process.env.OPENSHIFT_MONGODB_DB_USERNAME + ":" + process.env.OPENSHIFT_MONGODB_DB_PASSWORD + "@" + process.env.OPENSHIFT_MONGODB_DB_HOST + dbName;
console.log("conncetion string"+connection_string);
var db = mongojs(connection_string, ['location']);
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);
db.collection('location').insert({'city' : "sf",'id':'2'}, function(result){
console.log("success");
res.send(req.body.self);
// res.end('success');
});
};
$.ajax()
doesn't make realPOST
requests.I think it actually sends a
GET
request with theAccess-Control-Request-Method
Header set toPOST
.You can add support for this behavior by adapting your server-side code to match.