节点JS服务器中XMLHttpRequest发送的响应数据未定义

时间:2020-07-06 21:17:52

标签: javascript node.js xmlhttprequest

我正在尝试使用节点js和XMLHttpRequest()将数据保存在本地主机的数据库中 但是在服务器端,我无法通过XMLHttpRequest找到发送的数据,它向我显示response.body未定义。 我在客户端使用此代码发送数据。

 var http = new XMLHttpRequest(); 
 http.open("POST","http://localhost:3000/saveorderdata",true);
     var body = {
             "orderID":"11111111",
             "price":"10900", 
             "Name":"xxxxxx",
             "date":"24-4-20"
            })
     http.send(body);

在服务器端,我的index.js文件是

var mysql = require('mysql');
var express = require('express');
var bodyParser = require('body-parser');
var path = require('path');

var connection = mysql.createConnection({
    host     : 'localhost',
    port     : '3306',
    user     : 'root',
    password : 'mypassword',
    database : 'mysql'
});

var app = express();

var allowCrossDomain = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', "*");
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    next();
} 

app.use(bodyParser.json());

app.post('/saveorderdata', function(request, response) {
    console.log("request "+request.orderID);
    var orderID = request.body.orderID;
    var price = request.body.price;
    var Name = request.body.Name;
    var date = request.body.date;
    
    console.log(orderID+" "+ price);
    if (orderID||true) {
          connection.query('insert into orderData (orderID, price, Name, date) values (?,?,?,?)', [orderID, price, Name, date], function(error, result, fields) {
        if(error) {
          
          console.log('error: '+ error);  
          response.send('Database error!');
          response.end();

        } else {

          response.send("data enter successfully ");
          response.end();   
        } 


      });   
    }
});

app.listen(3000);
console.log('server running at - localhost:3000');

并且NULL保存在我通过XMLHttpRequest发送的thoes值插入的数据库中

1 个答案:

答案 0 :(得分:0)

您正在将对象传递给send,但是该函数不接受普通对象,因此它将转换为无用的字符串。

您还说了app.use(bodyParser.json());,但是:

  • 您不是是要发布JSON
  • 没有发布JSON

所以:

http.setRequestHeader("Content-Type", "application/json");
http.send(JSON.stringify(body));
相关问题