gpt4 book ai didi

javascript - 从ajax传递数据到node js时 undefined variable

转载 作者:太空宇宙 更新时间:2023-11-04 03:27:44 25 4
gpt4 key购买 nike

我试图将 amount 从 ajax 传递到 Node js,但我得到的只是 Node 服务器中未定义的。这是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){
});
}
}

console.log(string) 显示 {"amount": "1000"} 这对我来说看起来很正确。现在在 Node 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}`);
});

使用knockout js获取金额,因此self.amount()

最佳答案

如果您想使用 get,只需将内容类型更改为 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
});

关于javascript - 从ajax传递数据到node js时 undefined variable ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42463144/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com