Home > database >  Using Express and Axios, Axios will not recognize PUT Requests
Using Express and Axios, Axios will not recognize PUT Requests

Time:12-11

I have dumbed down my use case to a simple test, in which I click a button and an UPDATE put request is sent using an axios API. Three other request methods-- post, get, and delete, all work properly and are recognized. My PUT method, however, gives a 404 Not Found error, as though I havent established the method with express in my server.

This is the code for the request, triggered by this event handler (for the button):

const handleUpdate = async (e, id) => {
        e.stopPropagation();
        // navigate(`/restaurants/${id}/update`);
        //update test
        try {
            const updatedRestaurant = await RestaurantFinder.put(`/${id}`, {
                name: "taco bell",
                location: "dogtown",
                price_range: "2"
              });
              console.log(updatedRestaurant);
              navigate("/");
        } catch(err) {
            console.log(err);
        }
      };

This is the api's instantiation:

import axios from "axios";

export default axios.create({
    baseURL: "http://localhost:3001/api/v1/restaurants"
    }
);

This is the request in Express. Note that the first log "does this exist???" is never displayed. The address for the put request to "http://localhost:3001/api/v1/restaurants/id" is never found.

//UPDATE a restaurant
app.put("/api/v1/restaurants/:id"), async (req, res) => {
    console.log("does this exist???");
    try {
        const results = await db.query(
          "UPDATE restaurants SET name = $1, location = $2, price_range = $3 where id = $4 returning *",
          [req.body.name, req.body.location, req.body.price_range, req.params.id]
        );
    
        res.status(200).json({
          status: "succes",
          data: {
            restaurant: results.rows[0],
          },
        });
      } catch (err) {
        console.log(err);
      }
      console.log(req.params.id);
      console.log(req.body);
};

I have pored over StackOverflow for answers, I think I've viewed over 50 posts at this point. This is something that should be so simple, and yet I can't find a single answer for it or see where it's happening to anyone else.

If anyone could please help walk me through what is going wrong, I would be so grateful!

Edit 1 @Stephen:

const app = express();
app.use(cors(
  {
  methods: ["POST", "GET", "DELETE", "PUT"]
}
));
app.use(express.json());

So i changed it to this with no luck. Originally i was just using cors(), and my understanding is that it defaults to allowing a put method.

CodePudding user response:

Does your server allow the put method? Perhaps your server only allows the others in the access-control-allow-methods field.

See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Methods

For testing over http, make sure both of these are set by your server.

Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: PUT, GET, POST, DELETE, OPTIONS

CodePudding user response:

I was using a tutorial, and I went on the tutorial's github and copy and pasted the code. Below you will find my code followed by the code from the tutorial's github repo. Notice the misplaced parenthesis. Sorry, all..

//UPDATE a restaurant

app.put("/api/v1/restaurants/:id"), async (req, res) => {
  try {
      const results = await db.query(
        "UPDATE restaurants SET name = $1, location = $2, price_range = $3 where id = $4 returning *",
        [req.body.name, req.body.location, req.body.price_range, req.params.id]
      );
  
      res.status(200).json({
        status: "succes",
        data: {
          restaurant: results.rows[0],
        },
      });
    } catch (err) {
      console.log(err);
    }
    console.log(req.params.id);
    console.log(req.body);
};

Here's the code from the github repo of the tutorial:

// Update Restaurants

app.put("/api/v1/restaurants/:id", async (req, res) => {
  try {
    const results = await db.query(
      "UPDATE restaurants SET name = $1, location = $2, price_range = $3 where id = $4 returning *",
      [req.body.name, req.body.location, req.body.price_range, req.params.id]
    );

    res.status(200).json({
      status: "succes",
      data: {
        restaurant: results.rows[0],
      },
    });
  } catch (err) {
    console.log(err);
  }
  console.log(req.params.id);
  console.log(req.body);
});
  • Related