nodejs-get和post接收前端传递过来的参数
一、接收GET请求参数
在Node.js 中,处理GET请求时,参数通常会附加在URL的查询字符串中。你可以使用url模块或express框架来解析这些参数。
1、使用url模块
const http = require('http');
const url = require('url');
http.createServer((req, res) => {
const queryObject = url.parse(req.url, true).query;
console.log(queryObject);
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(' 参数已接收');
}).listen(3000);
2、使用express框架
const express = require('express');
const app = express();
app.get('/', (req, res) => {
const queryParams = req.query;
console.log(queryParams);
res.send(' 参数已接收');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
二、接收POST请求参数
处理POST请求时,参数通常会包含在请求体中。你可以使用body-parser中间件或express框架自带的解析功能来获取这些参数。
1、使用body-parser中间件
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.post('/', (req, res) => {
const bodyParams = req.body;
console.log(bodyParams);
res.send(' 参数已接收');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
2、使用express框架自带的解析功能
const express = require('express');
const app = express();
app.use(express.urlencoded({ extended: false }));
app.post('/', (req, res) => {
const bodyParams = req.body;
console.log(bodyParams);
res.send(' 参数已接收');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
前端要怎么传送数据呢?以fetch请求为例
get:
fetch("http://localhost:3300/?name=wuhuang&age=18") // 假设Node.js服务器运行在localhost的3300端口
.then((response) => response.json()) // 将响应数据转换为JSON
.then((data) => {
console.log(data);
}) // 处理得到的数据
.catch((error) => console.error("Error:", error)); // 处理错误
}
post:
fetch("http://localhost:3300/", {
method: "POST",
body: JSON.stringify({
name: "wuhuang",
age: "18",
}),
}) // 假设Node.js服务器运行在localhost的3300端口
.then((response) => response.json()) // 将响应数据转换为JSON
.then((data) => {
console.log(data);
}) // 处理得到的数据
.catch((error) => console.error("Error:", error)); // 处理错误
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】