简体   繁体   中英

How to make params in requests by axios into objects?

I have this code on a ReactJs app:

 axios
      .get(`/shipping/get-shipping-values`, {
        params: {
          products: [
            {
              ...product,
              quantity,
            },
          ],
          postalCode,
          cartTotalPrice: getProductPriceNumber(product.price) * quantity,
        },
      })
      .then((response) => {
        // do things with response
      })
      .catch((error) => {
        console.log(error);
      });

This is the console log of the products param in the express:

[ //Note above the ' that transform this object in an string.
  '{"package":{"weight":0.067,"width":5,"height":2,"length":2},"quantity":945}' 
]

Console log of products in the frontend :

[ package: { weight: 0.067, width: 5, height: 2, length: 2}, quantity: 945 ] 

As you can see, is an array but the object inside this array is an string.

I didn't change the default header of the axios, so is set to aplication/json.

I could use an JSON.parse() to make this string into an object. But I want to know if there is a way to make this automatic. That way I will not need to JSON.parse() every param that I send to the express server.

If you are using expressJS add app.use(express.json()); middleware, before the routes and you can find the entire object inside the req.body object, inside the route handler. Let me know if this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM