Handle Cross Domain Ajax Post In Node Js
My app.js has the below handler for post app.all('/', function (req, res, next) { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Headers',
Solution 1:
Use body-parser module to fetch the data, for example:
server.js:
var express = require('express');
var bodyParser = require('body-parser');
var db = require('./db'); //module that contains db connection configvar app = express();
app.use(bodyParser());
app.get('/', function(req, res) {
res.sendFile('/index.html', {root: __dirname });
});
app.post('/users', function(req, res) {
console.log(req.body); //req.body contains the user = {bla: 'bla'} objectvar user = req.body;
var collection = db.get('userlist');
collection.find(user, function (e, docs) {
res.json(docs);
});
res.send("Hey");
});
var server = app.listen(3000, function() {
console.log('listening');
});
index.html
<!DOCTYPE html><html><head><title></title></head><body><scripttype="text/javascript"src="https://code.jquery.com/jquery-2.1.4.min.js"></script><script>var user = { "bla":"bla" };
functioncheckUser(data) {
$.ajax({
type:"POST",
url: 'http://localhost:3000/users',
data: data,
dataType: "json"
}).success(function (data) { console.log(data) });
};
checkUser(user);
</script></body></html>
Post a Comment for "Handle Cross Domain Ajax Post In Node Js"