访问 Node.js 路由中的 req 参数在请求发送之前。

huangapple go评论51阅读模式
英文:

Accessing req parameters for` Node.js` route before request is sent

问题

在Node.js服务器路由中,获取GET请求数据的方式如下:

router.get("/dog", (req, res) => {
   // req.something...
});

出于调试目的,我想检查像以下这样的调用中作为req对象发送的内容:

fetch("/app/dog").then(/*...*/)

在发送请求之前,有没有办法让我访问**req参数**?(我可以在我的路由中进行调试,但我希望在进行fetch调用之前进行此检查)。谢谢!

英文:

In a Node.js server routes get request data as follows:

router.get("/dog", (req, res) => {
   // req.something...
});

For debugging purposes, I want to inspect what gets sent as the req object for a call like the following:

fetch("/app/dog").then(/*...*/)

Is there a way for me to access the req parameters before the request is sent? (Presumably I could do such debugging in my route, but I'm wanting to perform this inspection before making the fetch call). Thanks!

答案1

得分: 1

如果您使用fetch,可能希望为本机的window.fetch函数添加功能(方法),这在我看来不是一个好主意。最简单的方法是(在前端)使用已经提供请求拦截器的库,比如Axios

以下是一个示例,在这个示例中,我们将name=doggo作为请求参数发送,
然后在前端修改字符串为"doggo intercepted"
然后在后端使用Express中间件将该字符串修改为"doggo intercepted and middlewared"
最后在指定的路由处理程序中记录最终字符串:

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

<script>
// 添加一个请求拦截器
// https://axios-http.com/docs/interceptors
axios.interceptors.request.use((config) => {
  // 在发送请求之前做一些事情:
  // 修改参数名
  config.params.name += " intercepted"; // << 修改字符串 "doggo"
  console.log(config);
  return config;
}, (err) => Promise.reject(err));

// 初始化 GET 请求:
axios.get("/app/dog", {
  params: {
    name: "doggo"
  }
});
</script>
import express from "express";
import path from "path";
import url from "url";
const __dirname = url.fileURLToPath(new URL(".", import.meta.url));

const app = express();
const port = 3000;

// 创建一个中间件:
// https://expressjs.com/en/guide/using-middleware.html
app.use('/app/:animal', (req, res, next) => {
  // 如果路由是 "dog",则执行一些操作
  if (req.params.animal === "dog") {
    req.query.name += " and middlewared"; // << 修改字符串 "doggo intercepted"
  }
  // 继续执行下一个中间件或路由处理程序
  next();
})

app.get("/", (req, res) => {
  res.sendFile(path.join(__dirname, "/index.html"));
});

app.get("/app/dog", (req, res) => {
  console.log(req.query); // { name: 'doggo intercepted and middlewared' }
});

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
});
英文:

If you use fetch, you might want to add functionality (methods) to the native window.fetch function which is not a good idea IMHO.
The simplest is to use (on the frontend) a library that already provides request interceptors like Axios.

Here's an example in which we send name=doggo as a request param,
we than modify the string to &quot;doggo intercepted&quot; still on the frontend,
we than modify that string on the backend using Express Middleware to &quot;doggo intercepted and middlewared&quot; and finally log the final string in the designated route handler:

<sub>index.html</sub>

&lt;script src=&quot;https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js&quot;&gt;&lt;/script&gt;

&lt;script&gt;
// Add a request interceptor
// https://axios-http.com/docs/interceptors
axios.interceptors.request.use((config) =&gt; {
  // Do something before request is sent:
  // Modify param name
  config.params.name += &quot; intercepted&quot;; // &lt;&lt; modify the &quot;doggo&quot; string
  console.log(config);
  return config;
}, (err) =&gt; Promise.reject(err));


// Init GET request:
axios.get(&quot;/app/dog&quot;, {
  params: {
    name: &quot;doggo&quot;
  }
});
&lt;/script&gt;

<sub>index.js (Node)</sub>

import express from &quot;express&quot;;
import path from &quot;path&quot;
import url from &quot;url&quot;;
const __dirname = url.fileURLToPath(new URL(&quot;.&quot;, import.meta.url));

const app = express();
const port = 3000;

// Create a middleware:
// https://expressjs.com/en/guide/using-middleware.html
app.use(&#39;/app/:animal&#39;, (req, res, next) =&gt; {
  // If route &quot;dog&quot;, do something
  if (req.params.animal === &quot;dog&quot;) {
    req.query.name += &quot; and middlewared&quot;; // &lt;&lt; modify the &quot;doggo intercepted&quot;
  }
  // Pass through
  next();
})

app.get(&quot;/&quot;, (req, res) =&gt; {
  res.sendFile(path.join(__dirname, &quot;/index.html&quot;));
});

app.get(&quot;/app/dog&quot;, (req, res) =&gt; {
  console.log(req.query); // { name: &#39;doggo intercepted and middlewared&#39; }
});

app.listen(port, () =&gt; {
  console.log(`Example app listening on port ${port}`)
});

答案2

得分: -2

"no". The req parameter gets created after the request is sent by the client, and after it's headers are received by the server.

英文:

The short version is 'no'. The req parameter gets created after the request is sent by the client, and after it's headers are received by the server.

huangapple
  • 本文由 发表于 2023年6月15日 02:21:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/76476508.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定