Error code 405 (METHOD NOT ALLOWED) is received when attempting to make a post request to an API

Struggling to develop a basic front end that can communicate with my API. The API functions properly as I am able to retrieve and send data using the POSTMAN client. Fetching data from the server and displaying it on the frontend works fine, but encountering difficulties when attempting to post to the API.

Encountering this error message when trying to post the data: script.js:45

POST http://127.0.0.1:5500/users net::ERR_ABORTED 405 (Method Not Allowed)
(anonymous) @ script.js:45

Here is the form I am trying to submit:

<form>
First name: <input type="text" name="firstname" id="firstname"><br>
Last name: <input type="text" name="lastname" id="lastname"><br>
Age: <input type="number" name="age" id="age"><br>
<button type="submit">Send to backend</button>
</form>

The following JavaScript code is embedded in the frontend:

// function updatePost(){
const firstname = document.getElementById('firstname')
const lastname = document.getElementById('lastname')
const age = document.getElementById('age')
const button = document.querySelector('button')

button.addEventListener('click',(e)=>{
  e.preventDefault()
  var obj = {
    firstname: firstname.value,
    lastname: lastname.value,
    age: age.value
  };
  fetch('/users',{
    method: "POST",
    // headers:{
    //   "content-type":"application/json"
    // },
    body: JSON.stringify(obj)
  })
})
// }
// updatePost()

And here is the post route, which represents the server-side logic:

app.post('/users', async(req, res)=>{
var {firstname, lastname, age} = req.body
console.log(req.body)
let conn;
try {
    console.log(firstname, lastname, age)
    conn = await pool.getConnection()
    const result = await conn.query("insert into info (firstname, lastname, age) VALUES (?, ?, ?)", [firstname, lastname, age])
    res.json({
        "res": "Your code is working correctly."
    })

} catch (error) {
    res.send(error)
} finally {
    // await poolModule.releaseConn(conn);
    conn.release()
}
})

app.listen('3008',()=>{
console.log('Server is up and running')
})

Sensing that there might be something crucial that I am overlooking, any assistance will be highly appreciated. If you require additional information or further codes for troubleshooting purposes, feel free to request them. Thanks.

Answer №1

Are you currently utilizing the Live Server extension to open your HTML page? If so, keep in mind that Live Server is specifically designed as a static web server for serving assets like HTML, CSS, JavaScript, and images.

If you find yourself trying to send a POST request using

fetch('/users', { method: 'POST' })
, remember that Live Server may not be equipped to handle this type of request. It's recommended to direct such requests to your Express service instead.

Here are two possible solutions...

1. Incorporate Express into your workflow

Instead of relying solely on Live Server, consider using Express to serve your static content by following these steps:

app.use(express.static('path/to/html/files'));

Then, access your files via http://localhost:3008/... in your browser.

This approach ensures that any relative or path-only requests, like /users, are routed correctly.

Alternatively...

2. Implement CORS in your Express environment

To enable cross-origin requests, integrate CORS into your Express app by:

  1. Installing the cors middleware

    npm i cors
    
  2. Enabling CORS within your code

    import cors from 'cors'; // or const cors = require('cors')
    
    // ...
    
    // Activate CORS
    app.use(cors({
      origin: ['http://localhost:5500'],
    }));
    
    // Subsequently add other request-handling middleware, such as express.json()
    
  3. Sending your request to Express

    fetch('http://localhost:3008/users', {
      method: 'POST',
      headers: { 'content-type': 'application/json' },
      body: JSON.stringify(obj),
    })
    

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for adding a new property to an array object in TypeScript using a condition

Here is an array object that I have: arr = [ { Name: "ABC", Age: 20}, { Name: "XXX", Age: 15} ]; In Typescript, I am looking to dynamically add a new property called "Flag" with a value of 1 only if the Age is greater than 15. Can someone suggest ...

Having trouble with installing Angular JS on my computer

On my machine, I have successfully installed node.js version v0.12.0. However, when attempting to run sudo npm install, I encountered the following errors: npm ERR! install Couldn't read dependencies npm ERR! Darwin 14.0.0 npm ERR! argv "node" "/usr/ ...

Clickable elements are not functioning on dynamically generated divs

In the process of developing an application using Angular, I encountered a scenario where I needed to fetch and display data from a web service. The challenge was in dynamically creating div elements with the retrieved data: for(var i = 0 ; i < data.Ou ...

Making AngularJS work with angular-ui bootstrap and ensuring compatibility with IE8

Having trouble getting AngularJS code that utilizes angular-ui bootstrap to function properly in IE 8? Following the guidelines in the AngularJS developer guide on IE didn't seem to solve the issue for me. I inserted the code snippet below into my ind ...

What's the best way to update the fill color of an SVG dynamically?

Is it possible to change the color of an SVG image dynamically without using inline SVG tags? I want to create a code that allows users to specify the source for the SVG tag and a hexadecimal color value, enabling them to customize any SVG image with their ...

Can a complete form be encapsulated within a single AngularJS directive?

While I have come across several instances of individuals utilizing a blend of HTML and directives to craft an AngularJS form (as seen here), my goal is to develop a self-contained widget. This widget would encompass all the necessary HTML for the form w ...

Is there a way to use Node/Express to serve static files from React for a specific route exclusively?

Within my Express application's server.js file, I have imported a router using: const portfolio = require('./routes/portfolio') This router is then utilized with: app.use('/portfolio', portfolio); Inside the defined router, the ...

Connecting Laravel with Express Js

Greetings, I have a technical inquiry. I am proficient in Laravel but relatively new to Express Node. Currently, my code is functioning well with jQuery, but I need to convert it to Express. Should I install Express in the same folder as my Laravel project ...

Access the properties of a JSON object without specifying a key

I am dealing with a collection of JSON arrays structured like this: [ { team: 111, enemyId: 123123, enemyTeam: '', winnerId: 7969, won: 1, result: '', dat ...

Is there a way to streamline the import process for material-ui components?

Is there a shortcut to condense all these imports into one line? As a newcomer to react, I've noticed that every component must be individually imported, especially when it comes to CSS components. Could you provide me with a suggestion on how to st ...

What causes my paragraph textContent to vanish after briefly displaying its value?

As a beginner in JavaScript and HTML, I am taking on the challenge of learning these languages from scratch independently. I have encountered an issue with my code where the word "Hi!" briefly flashes below the "Click Me!" button before disappearing compl ...

Sending back the requested information in C to the ajax (jquery) CGI

After fetching specific data using C in my jQuery, how can I appropriately transfer the data to C? function Run() { $.ajaxSetup({ cache: false }); var obj = {"method":"pref-get","arguments":{"infos":["sys_info"]}}; alert("Post Json:" + JSO ...

The AudioContext feature is functioning properly on Google Chrome but experiencing issues on Safari

In Safari, I understand that audio context needs to be created after user interaction. Despite this knowledge, the code below still didn't produce the desired result. HTML <button onclick="play">Play</button> Javascript functio ...

jQuery live function is not functioning as anticipated

I am facing issues with ajax requests and simple <input type="submit"/>. I have a practice of loading views within other views, in a modular way, using jQuery's .load(url) function to move from one view to another. The problem arises when I loa ...

Is there a convenient method to combine arrays of objects in JavaScript using ellipses or an equivalent approach?

let array = [ {id: 1, data: {foo: "bar 1"}}, {id: 2, data: {foo: "bar 2"}} ]; //If ID doesn't exist, add new element to the array array = [...array, {id: 3, data: {foo: "bar 3"}}] console.log(array); //If ID exists, replace data object with new ...

How can I customize the appearance of the container and items in a dropdown <select> menu?

Im using contact form 7 on wordpress, i don't want to use a plugin rather use plain css/js to bring the results if possible. Something like this : https://i.stack.imgur.com/VTWRg.jpg ...

"Resolving the problem of populating an empty array with JSON

My JSON structure at the top level is set up like this: { "video": [], "messages": [], "notifications": [] } In the database output stored in a variable called "result," I have data that I want to add to the "vide ...

The page is undergoing a refresh and the query will not be executed - Ajax and PHP working together

function submitComment(ele) { event.preventDefault(); var username = "<?php echo $current_user; ?>"; var user_id = "<?php echo $current_user_id; ?>"; var post_id = $(ele).data('id'); var comments = $(ele).parent(".comment-se ...

What is the best way to refresh the slick jQuery plugin for sliders and carousels?

I am currently facing an issue with two buttons that have the same function. The purpose of these buttons is to retrieve data from an API, convert it to HTML, and then append it to a <div> using jQuery. Finally, the data is displayed using the slick ...

The behavior of Quasar's q-drawer is quite unpredictable

Having made the transition from Vue.js 2 with Vuetify to Vue.js 3 with Quasar due to Vuetify not officially supporting Vue.js 3 yet, I am utilizing q-drawer and its mini property. This allows me to toggle between the mini state and the normal expanded stat ...