Javascript 在Express server上获取从AJAX发送的数据
下面的代码使用AJAX请求通过express服务器发送数据。我需要访问发送后的数据,在我的express服务器上进行一些操作。我该怎么做呢 Express服务器代码段:Javascript 在Express server上获取从AJAX发送的数据,javascript,ajax,express,Javascript,Ajax,Express,下面的代码使用AJAX请求通过express服务器发送数据。我需要访问发送后的数据,在我的express服务器上进行一些操作。我该怎么做呢 Express服务器代码段: app.get("/time",function(req,res){ client.messages.create({ to: "+1" + req.data.number, from: '+166**', body: "This is the ship that m
app.get("/time",function(req,res){
client.messages.create({
to: "+1" + req.data.number,
from: '+166**',
body: "This is the ship that made the Kessel Run in fourteen parsecs?",
mediaUrl: "https://c1.staticflickr.com/3/2899/14341091933_1e92e62d12_b.jpg",
});
});
Ajax请求:
$.ajax({url: "/time",
data : { name : 'Justin', number : '662***' }
});
如果您正在谈论服务器中的GET变量:
app.get("/time",function(req,res){
client.messages.create({
to: "+1" + req.params.number, // should be `req.params` instead
from: '+166**',
body: "This is the ship that made the Kessel Run in fourteen parsecs?",
mediaUrl: "https://c1.staticflickr.com/3/2899/14341091933_1e92e62d12_b.jpg",
});
console.log(req.params.name)
console.log(req.params.number)
});
如果您说的是服务器的响应,则:
$.ajax({
url: "/time",
data : { name : 'Justin', number : '662***' }
}).done(function (response) {
console.log(response)
});
这个问题我已经读了3遍了,但仍然无法理解被问到了什么,很抱歉。如果您试图将数据发送到Express,您可能应该在Ajax调用中使用“POST”方法。然后,拥有一条与你拥有的路线一样的路线,但是
app.post
。您还应该在“发布”路径之前使用中间件
因此,您的服务器上应该有类似的东西(关于我所说的):
在Ajax调用中,只需添加一个“post”方法
@joaumg所说的关于req.params的内容也是正确的,但在我看来,这篇文章更正确。您的数据将更加安全。我尝试通过AJAX请求发送数据,然后在我的Express服务器中访问它。像通常在PHP中一样,我会使用$_GET来获取传输的数据,然后使用
req.params
而不是req.data
(;app.get是我当前在express服务器上使用的,因为它正在接受传入的请求。AJAX请求在另一个文件中。我知道AJAX请求在另一个文件中。我的观点是:发送数据,特别是敏感数据(不知道是否如此)您通常通过“post”来完成。您可以有另一个到同一uri的路由,但会收到一个“get”。这也会更有条理。
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/time', (req, res) => {
console.log(req.body); // your data here
})