K
K
kzoper2014-03-25 06:43:01
JavaScript
kzoper, 2014-03-25 06:43:01

How to implement data processing on the node.js server?

There is a script on the user page that ends up creating an array.

$(document).ready(function (){
  var data = [];
  $('#readyButton').click(function() {
    data[0] = $('#input_one').val();
    data[1] = $('#input_two').val();
  });
});

And there is a server that should process this request
var express = require('express');
var app = express.createServer(); 
app.use(express.bodyParser()); 
app.post('/', function(req, res){
  var obj = {};
  console.log('body: ' + JSON.stringify(req.body));
  res.send(req.body);
});  
app.listen(3000);

Can you please tell me how to send data to the server and return the result to the page?
Tried sending via AJAX.
$.ajax({
    type: 'POST',
    data: JSON.stringify(data),
    contentType: 'application/json',
                 url: 'http://blablabla.ru:3000/',						
                  success: function(data) {
                  console.log('success');
                  console.log(JSON.stringify(data));
         }

I get the following errors:
1) No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ' blablabla.ru ' is therefore not allowed access.
2) XMLHttpRequest cannot load

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Kuzmichev, 2014-03-25
@Assargin

I saw such an error (1) only in one case - when a cross-domain Ajax request is made that does not go through the same-origin policy , without the appropriate settings.
Error (2) is just a logical consequence (1)
Look at this , and in general Google for the query "crossdomain ajax".

K
karisters, 2014-04-07
@karisters

As said above, this is a cross-domain request that requires several requirements to be met.
First, the server must respond in a certain way to requests of the OPTIONS type. To do this, after the line
you need to add the following:

app.use(function (req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET, OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Origin, Content-type, Accept, Authorization');
    res.header('Access-Control-Allow-Credentials', 'true');
    next();
});

Second - on the client side, you need to execute a JSONP type request, which you need to read about here

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question