'Server responds with status 405
I'm running into a small issue with my "server". So while I'm trying to learn backend to frontend communication, I was messing around and trying to create an "api". Anyway, whenever I try to send a POST request, the server responds with net::ERR_ABORTED 405 error and doesn't print anything on the server. I use the VSC Live Server extension & run the server on my PC (while testing), not sure if that may effect anything.
Frontend:
<!DOCTYPE html>
<html>
<head>
<title>Testing</title>
<link href="https://fonts.googleapis.com/css2?family=Gemunu+Libre:wght@300&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Montserrat:100,200,300,400,500,600,700,800,900" rel="stylesheet">
<meta charset="UTF-8">
<link rel="stylesheet" href="style.css">
<link rel="icon" href="/img/Senko.jpg">
</head>
<body>
<script>
console.log("Running...")
const data = {
age: "15",
name: "John Doe",
date: "21/12/2021"
}
const options = {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data),
}
fetch("/api", options)
</script>
</body>
</html>
Backend
const express = require('express');
const app = express();
app.listen(5500, () => console.log('listening at 5500'));//Doesnt work no matter what I listen to.
app.use(express.static('public'));
app.use(express.json({ limit: '1mb' }));
const allData = [];
app.post('/api', (request, response) => {
const data = request.body;
allData.push(data);
response.json(allData);
console.log(allData);
});
The error message:
POST http://127.0.0.1:5500 net::ERR_ABORTED (Method not allowed)
I appreciate any help here.
Solution 1:[1]
You wrote you are using VSC live server. That doesn't make sense though, since you have your own backend. The live server extension will just serve your static files, so when your frontend attempts to POST to your API it will go to VSC live server, not your API, and it will tell you it doesn't support POST requests (plus, there is no public/api
folder)! But, you don't even need that extension, since your backend is also configured to serve the static files from public
.
Disable the live server extension and instead start your own backend, using npm start
in the shell. (Or, if you haven't configured the start
script in your package.json
yet - which you should - try node server.js
).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | CherryDT |