Answer the question
In order to leave comments, you need to log in
How to properly accept data in Node.js via Ajax?
Can you please tell me why the following code does not work?
Server:
var express =require('express'),
app = express();
var bodyParser = require('body-parser');
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
// routes
app.get('/', function(req, res, next) {
res.render('index');
});
app.post('/', function(req, res, next) {
console.log(req.body.title);
console.log(req.body.description);
});
var $form = $('#upload_file_form');
$form.on('submit', function(e) {
e.preventDefault();
var data = $form.serialize();
$.ajax({
url: 'http://localhost:5000/',
processData: false,
contentType: false,
type: 'POST',
data: data,
success: function() {
console.log('Success upload');
}
});
});
Answer the question
In order to leave comments, you need to log in
It's all CORS. It requires several headers from the server side:
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", req.headers.origin);
res.header('Access-Control-Allow-Credentials', 'true');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
var ajaxSettings = {
method: form.method,
url: form.action,
data: JSON.stringify(data),
// dataType: form.method === 'get' ? 'jsonp' : 'json',
dataType: 'json',
contentType: 'application/json',
processData: false,
xhrFields: {
withCredentials: true
}
};
var ajaxRequest = $.ajax(ajaxSettings);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question