W
W
Wasya UK2017-04-11 18:06:19
JavaScript
Wasya UK, 2017-04-11 18:06:19

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);
    
});


Customer:
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

1 answer(s)
A
Anton Anton, 2017-04-11
@dmc1989

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();
});

and on the client side:
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);

Well, or you can also distribute the front with the same node, then there will be no cross-domain request.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question