将数据从ajax传递到节点js时未定义的变量

时间:2017-02-26 00:03:14

标签: javascript ajax node.js knockout.js

我正在尝试将数量从ajax传递到节点js,但我得到的所有内容都未在节点服务器中定义。这是ajax代码。

self.information = function() {
    var x = {"amount" : self.amount()};
    var string = JSON.stringify(x);
    console.log(string);
      $.ajax({
          type: 'GET',
          url: 'http://localhost:3000/getIOT',
          contentType: 'application/json; charset=utf-8',
          dataType: 'json',
          data: string
      })
      .done(function(result) {
       console.log(result);
      })
      .fail(function(xhr, status, error) {
          console.log(error);
      })
      .always(function(data){
      });
  }
}

The console.log(string) shows {"amount" : "1000"}看起来对我而言。现在在节点js服务器中我试图查看变量名称,但它显示未定义。

const path = require('path');
const http = require('http');
const express = require('express');
const cors = require('cors');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var requestify = require('requestify');
var request = require('request');
var helmet = require('helmet');
var https = require('https');

var app = express();
app.use(helmet());

const publicPath = path.join(__dirname, '../public');
const port = process.env.PORT || 3000;

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());

app.use(express.static(publicPath));


app.get('/getIOT', function (req, res , err) {
            console.log('body: ' + JSON.stringify(req.body));
             // SHOWS {}  above
            var amount = req.body.amount;
            console.log(req.body.amount);
            // SHOWS UNDEFINED ABOVE 
});



app.listen(port, () => {
  console.log(`Server is up on ${port}`);
});

使用敲除js作为金额,因此self.amount()

2 个答案:

答案 0 :(得分:2)

如果你想使用get,只需将数据作为查询字符串发送,方法是将content-type更改为application / x-www-form-urlencoded并发送为json对象

如果你想张贴:

 amount=12&otherprop=xxx

更改为

 var x = {"amount" : self.amount()};
 $.ajax({
      type: 'GET',
      url: 'http://localhost:3000/getIOT',
      contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
      dataType: 'json',
      data: x
  });

在nodejs

使用req.query获取数据

app.get('/getIOT', function (req, res , err) {
            console.log('body: ' + req.query);
             // SHOWS {}  above
            var amount = req.query.amount;
            console.log(req.query.amount);
            // SHOWS UNDEFINED ABOVE 
});

答案 1 :(得分:1)

如果您使用HTTP GET请求,我相信jQuery的.ajax会在查询参数中发送数据。我要检查req.query而不是req.body,或者更改ajax调用为type: 'POST'以将其设置为req.body

如果这听起来像是一堆废话,我可以尝试更详细地解释:)