如何将数据作为Node.js服务器的响应发送到AJAX客户端?

时间:2021-11-19 15:54:14

So I'm calling this function to send data about an HTML element as an object:

所以我调用此函数将有关HTML元素的数据作为对象发送:

function postItem(input) {
  $.ajax({
    type: "POST",
    url: "http://localhost:8080",
    data: input,
    success: function(message) {
      Hconsole.log('got data back');
      var m = message;
      alert(m);
    },
    error: function(jqXHR, textstatus, errorThrown) {
      alert('text status ' + textstatus + ', err ' + errorThrown);
    }
  })
}

And the server is to compare the input object and an already stored object, and to respond with whether they're the same or not:

服务器将比较输入对象和已存储的对象,并回答它们是否相同:

app.post('/', (req, resp) => {
  var eObjClient = req.body;

  //somehow get data from database, the following is dummy data
  var eObjServer = {
    type: 'I',
    text: '',
    width: '70',
    height: '80',
    href: '',
    color: 'rgb(255, 255, 255)',
    class: 'icon-big icon ion-ios-analytics-outline'
  };

  /*
  Object.keys(eObjClient).forEach(function(key){
    console.log(key + ": " + eObjClient[key]);
  });
  */

  if (isSimilar(eObjClient, eObjServer)) {
    console.log('step working');
    resp.send('step working');
  } else {
    console.log('broken');
    resp.send('broken');
  }
  resp.end();
});

Currently the server gets the data and does the calculations fine, but the error message on the client side is always invoked and I don't know why. Additionally, I keep getting this error on the client side console if it helps:

目前服务器获取数据并进行计算,但客户端的错误消息总是被调用,我不知道为什么。此外,如果有帮助,我会在客户端控制台上不断收到此错误:

"Failed to load http://localhost:8080/: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access."

“无法加载http:// localhost:8080 /:请求的资源上没有'Access-Control-Allow-Origin'标头。因此不允许原点'null'访问。”

I'm using the libraries Express.js and body-parser. I'm a beginner to server stuff, any help would be greatly appreciated.

我正在使用库Express.js和body-parser。我是服务器的初学者,任何帮助都将非常感激。

3 个解决方案

#1


0  

It is because your client and server are cross domain and so the browser is blocking it.

这是因为您的客户端和服务器是跨域的,因此浏览器阻止它。

you could try in your Node.js:

你可以试试你的Node.js:

app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
});

However, it is important to note that it will allow any connection and should not be used in production.

但是,重要的是要注意它将允许任何连接,不应在生产中使用。

#2


0  

Just drop in CORS middleware and your client AJAX request should function properly. You can use this library: https://github.com/expressjs/cors in the following way:

只需放入CORS中间件,您的客户端AJAX请求就能正常运行。您可以通过以下方式使用此库:https://github.com/expressjs/cors:

var express = require('express')
var cors = require('cors')
var app = express()

app.use(cors())

#3


-1  

You should change your logic with:

你应该改变你的逻辑:

    let message = '';

    if(isSimilar(eObjClient, eObjServer)) {
      console.log('step working');
      message = 'step working';
    }
    else {
      console.log('broken');
      message = 'broken';
    }
    resp.status(200).send(message);

For your CORS problem I would recommend setting the appropiate headers or use cors library.

对于您的CORS问题,我建议您设置适当的标头或使用cors库。

#1


0  

It is because your client and server are cross domain and so the browser is blocking it.

这是因为您的客户端和服务器是跨域的,因此浏览器阻止它。

you could try in your Node.js:

你可以试试你的Node.js:

app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
});

However, it is important to note that it will allow any connection and should not be used in production.

但是,重要的是要注意它将允许任何连接,不应在生产中使用。

#2


0  

Just drop in CORS middleware and your client AJAX request should function properly. You can use this library: https://github.com/expressjs/cors in the following way:

只需放入CORS中间件,您的客户端AJAX请求就能正常运行。您可以通过以下方式使用此库:https://github.com/expressjs/cors:

var express = require('express')
var cors = require('cors')
var app = express()

app.use(cors())

#3


-1  

You should change your logic with:

你应该改变你的逻辑:

    let message = '';

    if(isSimilar(eObjClient, eObjServer)) {
      console.log('step working');
      message = 'step working';
    }
    else {
      console.log('broken');
      message = 'broken';
    }
    resp.status(200).send(message);

For your CORS problem I would recommend setting the appropiate headers or use cors library.

对于您的CORS问题,我建议您设置适当的标头或使用cors库。