如何将前端JS输入值传递给Node.js代理作为API请求的查询参数
实现步骤
1. 修改前端main.js,发送带查询参数的请求
你需要将获取到的inputValue作为查询参数,发送给本地的Node代理接口,示例代码如下:
const inputValue = document.querySelector('input').value // 示例值为maybeline // 发起请求到本地代理接口,将inputValue作为brand参数传递 fetch(`http://localhost:5500/api?brand=${encodeURIComponent(inputValue)}`) .then(res => res.json()) .then(data => { // 处理返回的接口数据 console.log(data) }) .catch(err => { console.error('请求出错:', err) })
注:使用encodeURIComponent是为了转义参数中的特殊字符,避免请求格式错误。
2. 修改Node代理app.js,接收参数并转发请求
在代理接口中读取前端传递的brand查询参数,拼接进第三方API的请求地址即可,同时修复原有代码中错误处理的变量名问题:
const express = require('express') const request = require('request'); const app = express() app.use((req,res,next)=>{ res.header('Access-Control-Allow-Origin', '*'); next(); }) app.get('/api', (req, res) => { // 读取前端传递的brand参数 const brand = req.query.brand // 非空校验,避免无效请求 if (!brand) { return res.status(400).json({ type: 'error', message: '缺少brand参数' }) } request( // 拼接brand参数到第三方请求地址 { url: `https://makeup-api.herokuapp.com/api/v1/products.json?brand=${encodeURIComponent(brand)}` }, (error, response, body) => { if (error || response.statusCode !== 200) { // 修复原有代码变量名错误:原变量是error不是err return res.status(500).json({ type: 'error', message: error.message }); } res.json(JSON.parse(body)); } ) }); const port = process.env.PORT || 5500 app.listen(5500,()=>console.log(`listening ${port}`))
相关可查阅的能力说明
- Express框架的请求对象
req.query用于读取GET请求的查询参数 - 前端
fetch API用于发起网络请求 encodeURIComponent用于转义URL中的特殊字符
内容的提问来源于stack exchange,提问作者Mal
相关产品推荐
相关产品推荐

