后端无法接收 Fetch API GET 请求中的 userUUID,如何解决?

新手上路,请多包涵

前端使用
await Fetch(/project/api/project/team/${teamInfo.uuid}/plugin/v1/project, {method: 'GET',data: { userUUID: userInfo.uuid , timestamp: Date.now()}}) 对后端发起请求

后端接收不到userUUID这个参数
下面是后端代码
export async function getProjectList(request: PluginRequest): Promise<PluginResponse> {

const body = request.body as any

Logger.info('[Plugin] hello ======= 请求成功')
return {
  body: {
    res: 'xxx',
    requestBody: request,
  },
}
  

}

希望得到解决

阅读 676
2 个回答

解决方法建议:

使用GET请求:

  • 如果是GET请求,前端做法参数需要放在URL的查询字符串中,而不是在data字段中。例如:
await fetch(`/project/api/project/team/${teamInfo.uuid}/plugin/v1/project?userUUID=${userInfo.uuid}&timestamp=${Date.now()}`, {
     method: 'GET',
   });
  • 后端做法可以直接解析GET请求的查询参数,可以通过request.query(而不是request.body)来获取。例如:
export async function getProjectList(request: PluginRequest): Promise<PluginResponse> {
     const query = request.query; // 获取查询参数
     const userUUID = query.userUUID;
     const timestamp = query.timestamp;

     Logger.info(`[Plugin] 请求成功: userUUID=${userUUID}, timestamp=${timestamp}`);
     
     return {
       body: {
         res: 'xxx',
         requestQuery: query,
       },
     };
   }

使用POST请求:

  • 如果参数较复杂,或者不适合放在查询字符串中,可以改用POST请求,前端做法将参数放在body中。例如:
await fetch('/project/api/project/team/${teamInfo.uuid}/plugin/v1/project', {
     method: 'POST',
     headers: {
       'Content-Type': 'application/json',
     },
     body: JSON.stringify({
       userUUID: userInfo.uuid,
       timestamp: Date.now(),
     }),
   });
  • 后端做法解析body参数:
export async function getProjectList(request: PluginRequest): Promise<PluginResponse> {
     const body = request.body as any;
     const userUUID = body.userUUID;
     const timestamp = body.timestamp;

     Logger.info(`[Plugin] 请求成功: userUUID=${userUUID}, timestamp=${timestamp}`);

     return {
       body: {
         res: 'xxx',
         requestBody: body,
       },
     };
   }

总结

  • 如果坚持使用GET请求,参数放在URL查询字符串中。
  • 如果需要更复杂的参数传递,推荐使用POST请求并传递JSON数据。

GET 请求用 body 传参?

倒不是不行,HTTP 协议的 RFC 规范本身并没有规定 GET 请求不能携带请求体,事实上有些服务还真就是在 GET 请求体里携带参数的(比如 ElasticSearch)。

但问题那是后端与后端之间通信,前端你是跑在浏览器里的,浏览器的 AJAX 实现中 GET 请求的请求体可是会被直接丢弃掉的。

要么你就改成 POST 请求;要么你就改成从 query 传参。“既要、又要”是不行的。

推荐问题