React App + Express JS Server + Axios 前端请求 = 服务器上的 “undefined” 选项参数

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

React App + Express JS Server + Axios frontend request = "undefined" options params on Server

问题

这是前端代码:

export const getBlog = (sortColumn, sortOrder) => async dispatch => {
  
 console.log("blogActions.js => getBlog() executed.");
 console.log("sortColumn = " + sortColumn);
 console.log("sortOrder = " + sortOrder);

 let options = {
            order: [sortColumn, sortOrder]
            };
            
  try{
  // 调用API,从端点获取所有反馈。
  const res = await axios.get('/api/blog', options);
  /*
  {
    params: {
      sortColumn: "Heading", 
      sortOrder: "ASC"
        }
    } */
  );

这是后端代码:

router.get('/', async (req, res) => {
    console.log('/api/blog - get');
    
    // 返回所有博客。
    // 我们需要查询数据库以获取我们的数据。
    // 我们将使用findAll()函数来执行此操作,以获取反馈表中的所有反馈。
    // 注意:如果我们使用await,我们需要在(req, res)之前加上async。

    console.log("req.query = " + req.query);
    console.log("req.params = " + req.params);
    //const { sortColumn, sortOrder} = req.params;
    const { sortColumn, sortOrder} = req.query;
    console.log(sortColumn);
    console.log(sortOrder);

    try{
    const list = await Blog.findAll(
      /*
      {
      order: [[sequelize.col(sortColumn)]]
      } 
    */
    );

    // 将列表发送回客户端。
    res.send(list);
    }
    catch(e)
    {
        console.log(e); // 错误
    }

  });

请注意,我已经删除了HTML实体字符(例如"和'),以便更容易阅读。

英文:

I have Googled this problem over and over and can't seem to find the solution.

Here is my frontend code:

export const getBlog = (sortColumn, sortOrder) => async dispatch => {
  
 console.log("blogActions.js => getBlog() executed.");
 console.log("sortColumn = " + sortColumn);
 console.log("sortOrder = " + sortOrder);

 let options = {
            order: [sortColumn, sortOrder]
            };
            

  try{
  // call the api. Get all our feedback from our endpoint.
  const res = await axios.get('/api/blog', options

    
  /*
  {
    params: {
      sortColumn: "Heading", 
      sortOrder: "ASC"
        }
    } */
  );

Here is my backend code:

router.get('/', async (req, res) => {
    console.log('/api/blog - get');
    
    // Return all blog.
    // We need to query our database to get our data.
    // We will do this by using the findAll() function, to get all the feedback in the feedbacks table.
    // Note: Remember if we use await, we need an async before(req, res).

    console.log("req.query = " + req.query);
    console.log("req.params = " + req.params);
    //const { sortColumn, sortOrder} = req.params;
    const { sortColumn, sortOrder} = req.query;
    console.log(sortColumn);
    console.log(sortOrder);


    try{
    const list = await Blog.findAll(
      
      /*
      {
      order: [[sequelize.col(sortColumn)]]
      } 
    */
    );

    // send the list back to the client.
    res.send(list);
    }
    catch(e)
    {
        console.log(e); // error
    }

  });

The req.query and req.params on the backend both result in "undefined".

Any ideas how to solve this problem?

Kind Regards,

John
Melbourne, Australia

This is the debugging output on the server when requesting data from the frontend client:

frontend request, VS Code server console

I have tried using Postman and the params get passed through just fine, as you can see here:
Postman

VS Code server console

答案1

得分: 0

Axios 用于 URL 查询参数的选项是 params...

> params 是要与请求一起发送的 URL 参数
> 必须是普通对象或 URLSearchParams 对象

查看 Axios - 请求配置

如果你希望在 req.query 中接收到 sortColumnsortOrder 参数,你需要像这样构建你的选项

axios.get("/api/blog", { params: { sortColumn, sortOrder } })

不过,需要注意的是,某些版本的 Axios 在处理 URL 查询序列化方面存在 bug。我始终建议使用 Fetch API 而不是 Axios。

const baseURL = process.env.REACT_APP_API_BASE_URL;
// 或者 "http://localhost:3001/",等等

const url = new URL("/api/blog", baseURL);
url.searchParams.append("sortColumn", sortColumn);
url.searchParams.append("sortOrder", sortOrder);

const res = await fetch(url);
const data = await res.json();

如果你想要使用 req.params,你需要使用路由参数定义你的路由

router.get("/:sortColumn/:sortOrder", (req, res) => {
  const { sortColumn, sortOrder } = req.params;

  // ...
});

然后像这样发送请求

axios.get(
  `/api/blog/${
    encodeURIComponent(sortColumn)
  }/${
    encodeURIComponent(sortOrder)
  }`
)

对于这种类型的请求,我不建议使用这种方法。

英文:

The Axios option for URL query parameters is params...

> params are the URL parameters to be sent with the request
> Must be a plain object or a URLSearchParams object

See Axios - Request Config

If you expect to receive sortColumn and sortOrder params in req.query, you'll need to construct your options like this

axios.get("/api/blog", { params: { sortColumn, sortOrder } })

A word of warning though, some versions of Axios have a bug around URL query serialisation. I would always recommend using the Fetch API instead of Axios.

const baseURL = process.env.REACT_APP_API_BASE_URL;
  // or "http://localhost:3001/", etc

const url = new URL("/api/blog", baseURL);
url.searchParams.append("sortColumn", sortColumn);
url.searchParams.append("sortOrder", sortOrder);

const res = await fetch(url);
const data = await res.json();

If you wanted to use req.params, you'd need to define your route with route parameters

router.get("/:sortColumn/:sortOrder", (req, res) => {
  const { sortColumn, sortOrder } = req.params;

  // ...
});

and send the request like this

axios.get(
  `/api/blog/${
    encodeURIComponent(sortColumn)
  }/${
    encodeURIComponent(sortOrder)
  }`
)

I would not recommend this method for this type of request.

答案2

得分: -1

尝试将您的axios get请求更改为以下内容,请求查询应该在req.query中存在:

axios.get(`/api/blog?sortColumn=${sortColumn}&sortOrder=${sortOrder}`);
英文:

try change your axios get to this, the req query should be there in req.query

axios.get(`/api/blog?sortColumn=${sortColumn}&sortOrder=${sortOrder}`);

huangapple
  • 本文由 发表于 2023年7月10日 12:43:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/76650718.html
匿名

发表评论

匿名网友

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

确定