Reputation: 2444
I have a node.js server with Express and Socket.io. In The Socket.io docs i found this example code for host server.
My problem is now the next: I cant read Post data from the requests.
There is a request:
$.ajax({
type: "POST",
url: "http://127.0.0.1:4444/login",
data: {
da: 'a'
},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){
console.log(data);
},
failure: function(errMsg) {
console.log(data);
}
});
And this is the server:
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(4444);
var database = require('./database.js');
database.methods.connect();
// Add headers
app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8080');
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);
next();
});
app.post('/login', function(req, res) {
console.log(req.body);
});
I tried a lot of thinks. For example: bodyParser.json(), bodyParser.urlencoded
But this express is run with require("http");
How can i read the body from the request? I hope someone can help me! Thanks
Upvotes: 1
Views: 1692
Reputation: 512
You need to add the Express body-parser middleware, something like this:
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(4444);
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
app.use(function (req, res) {
res.setHeader('Content-Type', 'text/plain')
res.write('you posted:\n')
res.end(JSON.stringify(req.body, null, 2))
})
Upvotes: 2
Reputation: 2444
chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security
Upvotes: 0
Reputation: 1411
You must use body-parser
for express.
Documentation is here
var bodyParser = require('body-parser')
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }))
Upvotes: 1