使用Axios发送DELETE请求遇405错误,POSTMAN测试正常的解决问询
Hey there! Let's break down why your Axios DELETE request is failing and how to fix it.
The Core Issue
Looking at your Axios code, the main problem is how you're constructing the request URL. You're using '/api/flavour/{id}' with single quotes—this treats {id} as a literal string instead of replacing it with the actual id value passed into the function. That means your request is being sent to localhost:5000/api/flavour/{id} instead of the correct URL with your target document ID, which explains the 404/405 errors you're seeing.
Correct Axios Implementation
You need to use template literals (backticks ` instead of single quotes) to dynamically inject the id into the URL path. Here's the fixed code:
DeleteFlavour: async (id) => { console.log(id); // Use template literals to insert the actual id into the URL let res = await axios.delete(`/api/flavour/${id}`); console.log(res); return res.data || []; }
Why Your Previous Attempts Didn't Work
- When you tried passing the
idin Axios' second parameter, you were adding it as a query parameter (?id=xxx), but your backend is set up to expect it as a path parameter (/:id). These are two distinct URL formats, so the backend couldn't match the route. - Hardcoding the URL likely failed because you either kept the placeholder
{id}instead of using the actual ID value, or there was a subtle typo in the URL structure that didn't align with the backend route.
Additional Checks (If Issues Persist)
If you still run into problems after fixing the URL:
- Verify your Axios instance has the correct
baseURLset tolocalhost:5000(so/api/flavour/${id}resolves to the full valid URL). - Double-check that there are no method mismatches: Axios uses
.delete()and your backend usesapp.delete()—method conflicts are a common cause of 405 errors. - Confirm the ID you're passing matches exactly with a valid document ID in your database (invalid IDs might return unexpected status codes even with a correct URL).
内容的提问来源于stack exchange,提问作者BC2

