如何向本地Express服务器发送HTTP GET请求并获取请求值?
解决你的Express服务器GET请求问题
Hey there! Let's break down your two questions and fix your code step by step to get your local server and client talking smoothly.
一、本地连接服务器的URL应该填什么?
你的Express服务器运行在本地的4001端口,所以客户端发起请求的完整URL是 http://localhost:4001/question。这里的localhost是本地回环地址,指向你自己的电脑,:4001就是你代码里设置的服务端口号。
修改后的客户端代码应该是这样的:
$(document).ready(function () { $('.item').on('click', (element) =>{ // 填入完整的本地服务URL $.get("http://localhost:4001/question") .done(function(response) { // 可以在这里处理服务器返回的响应 console.log("Server response:", response); }) .fail(function(error) { // 处理请求失败的情况 console.error("Request failed:", error); }); }) })
二、如何从GET请求中获取"something"值?
这取决于你想怎么传递这个"something"值,常见的有两种实用方式,我都给你演示一下:
方式1:使用查询参数(Query Params)
客户端在URL后面通过?key=value的形式传递参数,比如把"something"作为查询参数传过去:
$(document).ready(function () { $('.item').on('click', (element) =>{ // 假设要传递的something值是"hello-local-server" $.get("http://localhost:4001/question?something=hello-local-server") .done(function(response) { console.log("Server response:", response); }); }) })
服务端通过req.query.something来获取这个参数,修改你的服务端代码:
const express = require('express'); const app = express(); const PORT = 4001; app.get("/question",(req, res, next) => { // 获取查询参数里的something值 const receivedSomething = req.query.something; console.log("Got something from client:", receivedSomething); // 可以把收到的值再返回给客户端 res.send(`Received your value: ${receivedSomething}`); }) app.listen(PORT, () =>{ console.log(`Server running on http://localhost:${PORT}`); })
方式2:使用路径参数(Route Params)
如果想把"something"作为URL路径的一部分,需要先修改服务端的路由,用:参数名来定义动态路径:
const express = require('express'); const app = express(); const PORT = 4001; // 路由里添加:something作为路径参数 app.get("/question/:something",(req, res, next) => { // 通过req.params获取路径参数 const receivedSomething = req.params.something; console.log("Got something from client:", receivedSomething); res.send(`Received your value: ${receivedSomething}`); }) app.listen(PORT, () =>{ console.log(`Server running on http://localhost:${PORT}`); })
客户端请求的URL就要改成包含具体值的路径,比如:
$(document).ready(function () { $('.item').on('click', (element) =>{ // 把要传递的something值直接放在URL路径里 $.get("http://localhost:4001/question/hello-local-server") .done(function(response) { console.log("Server response:", response); }); }) })
小提醒
记得先启动你的Express服务器(运行服务端代码),再点击页面上的.item元素发起请求,这样就能在控制台看到日志和交互结果啦!
内容的提问来源于stack exchange,提问作者Michal333
相关产品推荐
相关产品推荐

