Failed to load resource: the server responded with a status of 405 (Method Not Allowed)
Asked by Sai Siva Kumar about a year ago
1
I was tyring to send a POST request to node server. Server sedding me 405 status code.
1//browser// 2const button = document.getElementById("button"); 3const username = document.getElementById("username").value; 4const password = document.getElementById("password").value; 5let result; 6 7 8button.onclick = async function() { 9 result = await fetch("/app/login", { 10 method: "POST", 11 headers: { 12 "Contenty-type": "application/json" 13 }, 14 body: JSON.stringify({ 15 username, 16 password 17 }) 18 }).then((e) == > console.log(e)) {}) 19}
1//server// 2const http = require("http"); 3 4const app = http.createServer(async(req, res, next)=>{ 5 const postData = []; 6 7 if(req.url === "/api/login" && req.method === "POST"){ 8 for await(const chunk of req){ 9 postData.push(chunk) 10 } 11 const {username, password} = JSON.parse(Buffer.concat(postData).toString()); 12 if(!username){ 13 res.write(JSON.stringify({message:"username must be write"})) 14 }else if(!password){ 15 res.write(JSON.stringify({message:"password must be written"})) 16 } 17 else{ 18 res.write(JSON.stringify({message:"account created"})) 19 } 20 console.log({username, password}) 21} 22res.end(); 23}) 24 25app.listen(9966, ()=>{ 26 console.log(9966) 27})
1 Answer
0
Hey Sai! I've formatted and edited the code you've posted. Please use the following syntax to post code in the description.
``` <language name>
<your code here>
```
Coming to your query, it seems like you're posting the login data to /app/login but the server expects a post on /api/login.
Do checkout https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/405 to know more about the returned status code.
show more answers
Your answer