javascriptnode.jsexpressbackend

How to Configure NODEJS Express Server to accept POST Request


So, I am working on this quiz app that uses the Gemini API for formulating questions. My frontend uses HTML, CSS & JavaScript (Vanilla), while my backend is based on Node.JS (Express)

Whenever I send a fetch request, using the Fetch API, with the form inputs from the user, I always get this response on the console;

POST http://127.0.0.1:5500/genQuestions net::ERR_ABORTED 405 (Method Not Allowed)

See relevant index.js fetch request below:

await fetch('http://127.0.0.1:5500/genQuestions', { // On the console, this line is usually marked red
    method: 'POST',
    headers: {
      "Content-type": "application/json"
    },
    body: JSON.stringify(formObj), // The form Data Object
  })
  .then(response => {
    // Handle the server's response   
  })

Express JS:

// Setting up CORS this way
const cors = require('cors');
app.use(cors());
// Receive Post Requests
app.post('/genQuestions', async (req, res) =>{
  const formData = req.body;

  // Generate questions
})

My File structure, with the relevant files are shown below: Image showing the project file structure

My question is, how do i get my server to receive post requests? I feel like being able to modify the 'Allow: GET, HEAD, OPTIONS' to include 'POST' (See Response Header below) should help but I don't really know how to modify that.

I appreciate any advice I can get. Like I said earlier, I am new to NodeJS

See the network tab's response headers below:

// Response Header from Network Tab
HTTP/1.1 405 Method Not Allowed
Access-Control-Allow-Origin: http://127.0.0.1:5500
Vary: Origin
Access-Control-Allow-Credentials: true
Allow: GET, HEAD, OPTIONS
Content-Length: 0
Date: Mon, 17 Jun 2024 11:09:23 GMT
Connection: keep-alive
Keep-Alive: timeout=5

For those asking, I have included my index.js and server.js file in this Codepen. It won't run there but I believe you will be able to see my current code that gives out the "405 Method not Allowed" message. Link to Codepen


Solution

  • First thing is you are requesting for gen_questions in fetch request but in your server it is defined as genQuestions. Second is you are using 127.1.1.0..Instead use localhost in your fetch request.Let me know if it works.I tested it at my end and it works perfectly.