最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Next.js server action not receiving correctly decimal numbers - Stack Overflow

programmeradmin6浏览0评论

I'm facing an issue in my Next.js application where I'm passing a decimal number (as a string) as a query parameter to my API. The API works fine when tested directly using Swagger and also works when I send the request without using server actions.

However, when using server actions, the decimal number seems to be sent as an integer (for example, 2.5 becomes 25), and this causes the request to fail.

Here's how I'm calling the server action:

"use server";
async function fetchData() {
  try {
    const response = await fetch(`${process.env.API_URL}/endpoint?amount=2.5`, {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${process.env.ACCESS_TOKEN}`,
      },
    });

    if (!response.ok) {
      throw new Error("Network response was not ok");
    }

    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error("Error:", error);
  }
}

Issue:

  • When I pass the amount as a decimal number (e.g., 2.5), my API receives 25 instead.

  • This only happens when using the server action to make the request.

  • The same request works perfectly fine when I send it directly
    (without using server actions) like so:

    async function fetchData() {
      try {
        //using NEXT_PUBLIC_API_URL for browser visibility
        const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/endpoint?amount=2.5`, {
          method: "GET",
          headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${process.env.NEXT_PUBLIC_ACCESS_TOKEN}`, //using NEXT_PUBLIC_ACCESS_TOKEN for browser visibility
          },
        });
    
        if (!response.ok) {
          throw new Error("Network response was not ok");
        }
    
        const data = await response.json();
        console.log(data);
      } catch (error) {
        console.error("Error:", error);
      }
    }
    

Both the NEXT_PUBLIC_API_URL and API_URL are the same, and the tokens (NEXT_PUBLIC_ACCESS_TOKEN and ACCESS_TOKEN) are also the same.

What could be causing the decimal value to be transformed incorrectly when passed through a server action? How can I ensure the decimal value is sent correctly in the query parameter when using server actions?

versions that I am using "next": "14.2.3", "react": "18.2.0",

EDIT: Answer - I was missing 'Accept-Language' header and without this API was not behaving correctly when using server cation

发布评论

评论列表(0)

  1. 暂无评论