node.js中获取前端传递的get、post请求参数

req.query:get请求;

req.body:post请求;

(1) get请求:

req.query;

 (2) post请求:

     第一步:下载body-parser模块

npm install body-parser --save-dev

     第二步:引入body-parser模块

const bodyParser = requier("body-parser");

     第三步:使用body-parser模块

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

     第四步:使用body-parser模块的参数json方法

app.use(bodyParser.json());

     第五步:获取参数

req.body;

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以为你提供一个基本的 Node.js 模块,它封装了 get 和 post 请求,并支持传递 URL、数据、cookie 等参数。你可以在前端使用 axios 或其他 HTTP 客户端库来调用这个模块。 首先,你需要安装一些 Node.js 模块: ``` npm install request request-promise tough-cookie ``` 然后,你可以创建一个名为 `http.js` 的文件,内容如下: ```javascript const request = require('request-promise'); const tough = require('tough-cookie'); class HttpClient { constructor() { this.cookieJar = new tough.CookieJar(); } async get(url) { return this.sendRequest('GET', url); } async post(url, data) { return this.sendRequest('POST', url, data); } async sendRequest(method, url, data) { const options = { method: method, uri: url, headers: { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3', }, jar: this.cookieJar, json: true, }; if (data) { options.body = data; } try { const response = await request(options); return response; } catch (error) { console.error(`Failed to send ${method} request to ${url}`, error); throw error; } } } module.exports = HttpClient; ``` 这个模块使用了 request-promise 和 tough-cookie 库,它提供了一个 `HttpClient` 类,它有两个方法:`get` 和 `post`。这两个方法都接受一个 URL 参数和一个可选的数据参数。如果你需要在请求设置 cookie,可以调用 `setCookie` 方法来设置。 然后,你可以在你的 Node.js 代码使用这个模块,例如: ```javascript const HttpClient = require('./http'); const client = new HttpClient(); client.setCookie('my-cookie-name', 'my-cookie-value'); client.get('https://example.com') .then(response => { console.log('Response:', response); }) .catch(error => { console.error('Error:', error); }); ``` 如果你想在前端使用这个模块,你需要将它打包成一个 JavaScript 文件,然后在 Vue.js 引入它。这个过程可能有点复杂,但是你可以使用工具如 webpack、rollup、parcel 等来完成它。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值