Nodejs post数据以后页面没有刷新
Nodejs post数据以后页面没有刷新
$.ajax({url:“http://127.0.0.1:3000/test",data:{“hello”:"abc”}},function(d){alert(d)});
});
我用ajax发一个data,然后用express这么写:
//.../routes.js
exports.test = function(req,res){
console.log(req.query);
res.send(200,'hello world:\n'+req.query);
}
在服务器端看到
{ hello: 'abc' }
GET /test?hello=abc 200 1ms - 28b
但是在客户端就没有 hello world出现
这是为什么
Node.js POST 数据后页面没有刷新
问题描述
你使用了 jQuery 的 $.ajax
方法发送了一个 POST 请求到服务器,并且在客户端期望看到服务器返回的 “hello world”。然而,实际上你没有看到预期的结果。
原因分析
-
请求方法不匹配:你在客户端使用的是
POST
方法,但在服务器端却通过req.query
来获取数据。req.query
是用来处理 GET 请求中的查询参数(即 URL 中的参数)。对于 POST 请求,应该使用req.body
来获取请求体中的数据。 -
缺少 body-parser 中间件:如果你使用 Express 框架,你需要使用
body-parser
或者内置的中间件来解析请求体中的 JSON 数据。默认情况下,Express 并不会解析 POST 请求体中的数据。
解决方案
首先,确保你已经安装了 body-parser
中间件:
npm install body-parser
然后,在你的 Express 应用中使用 body-parser
中间件:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
// 使用 body-parser 中间件
app.use(bodyParser.json()); // 用于解析 JSON 格式的请求体
app.use(bodyParser.urlencoded({ extended: true })); // 用于解析 URL 编码的请求体
// 定义路由
app.post('/test', (req, res) => {
console.log(req.body); // 打印请求体中的数据
res.send(`hello world:\n${JSON.stringify(req.body)}`); // 返回响应
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
接下来,修改客户端的 AJAX 请求,确保它是一个 POST 请求:
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$.ajax({
url: "http://127.0.0.1:3000/test",
type: "POST", // 明确指定这是一个 POST 请求
data: {"hello": "abc"},
success: function(d) {
alert(d);
}
});
</script>
总结
- 确保在服务器端使用
req.body
而不是req.query
来处理 POST 请求的数据。 - 使用
body-parser
中间件来解析请求体中的数据。 - 在客户端明确指定请求类型为
POST
。
这样,你应该能够正确地接收到服务器返回的 “hello world” 响应。
jQuery API先搞懂
+1
用ajax请求会发生什么
根据你的描述,问题出在你使用的是 $.ajax
发送 POST 请求,但你在 Express 路由处理函数中读取的是 req.query
,这实际上是用于获取 GET 请求中的查询参数。对于 POST 请求,你需要从 req.body
中获取数据。
你可以通过以下步骤来解决这个问题:
- 确保使用 body-parser 解析请求体:你需要安装并配置
body-parser
中间件,以便解析 POST 请求的数据。 - 修改路由处理函数:将
req.query
替换为req.body
来获取 POST 请求中的数据。
示例代码
首先,确保在项目中安装了 body-parser
:
npm install body-parser
然后,在你的 Express 应用中配置 body-parser
:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
// 使用 body-parser 中间件解析 JSON 数据
app.use(bodyParser.json());
// 假设你的 routes.js 文件是这样配置的
app.post('/test', (req, res) => {
console.log(req.body); // 现在可以正确获取 POST 请求的数据
res.send(`hello world:\n${JSON.stringify(req.body)}`);
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
接下来,确保你的 AJAX 请求是发送 POST 请求而不是 GET 请求:
$.ajax({
url: "http://127.0.0.1:3000/test",
method: "POST", // 明确指定 POST 方法
data: {"hello": "abc"},
success: function(data) {
alert(data);
}
});
解释
- body-parser:它会解析 HTTP 请求体(通常是 JSON 格式),并将解析后的数据存放在
req.body
中。 - method 属性:在 AJAX 请求中明确指定
method: "POST"
,确保数据以 POST 方式发送。
通过这些更改,你应该能够在客户端看到正确的响应结果。