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

Using PATCH method in a restful API with Node.js

How do I properly use the PATCH verb in a REST API with Node.js Express? I'm struggling to understand how to implement it on the server side. How does the server know which specific field needs to be updated? What should the HTML request look like and ...

HTML and Javascript Form Integration for Sage Pay Purchase Button

Currently, I am working on a project that includes online payment options via PayPal and Google Wallet, with a "buy now" button. Now, my next step is to incorporate the Sage Pay "buy now" button onto the website using HTML and JavaScript. Although I have ...

Sending a JSON request using Swift 3

I am in need of posting JSON data that has the following structure: { "orders":[ {"id": 208, "quantity": 1 },{"id": 212, "quantity": 2},{"id": 202, "quantity": 5}, ...etc ],"HHStatus": "1 } Currently, I have a variable called orders : [ShoppingCart] = [] ...

Postman Guide: Mastering the Evaluation of JSON Arrays

One of the features in Postman allows users to save a specific field from the response body as a variable and then utilize that variable in a subsequent call. For instance, after my initial call to the web service, the response body contains: [ { "id" ...

How to Redirect a Webpage to the Same Tab in ASP.NET

I am currently using an asp.net hyperlink control to direct users to a web URL when the hyperlink is clicked. My goal is for the user to open a new tab, rather than a new window, when they click the hyperlink. If the user clicks the link again, I want th ...

The basic evaluation of jQuery elements does not result in a comparison

Wondering what's going wrong in this code: employee_ids = $('[data-employee_id="'+employee+'"]'); timestamp_ids = $('[data-scheduled_on="'+timestamp+'"]'); var common = $.grep(timestamp_ids, function(element) ...

What is the best way to transfer information from the window method to the data function in a Vue.js application?

Is there a way to transfer information from the window method to the data function in a vuejs component? Take a look at my window method: window.authenticate = function(pid, receiptKey) { console.log("Authentication"); console.log(this) localStorag ...

Unable to serve multiple static folders in ExpressJs is a current issue that needs

I am looking to organize my public folder in the following structure: - public - frontend - backend - assets # containing common CSS and JS static files for backend/frontend If the request includes /admin in the URL, I want to serve ...

The most recent release of Chrome (Version 47.0.2526.80 m) introduces an intriguing feature. When using navigator.webkitGetUserMedia, the returned stream now lacks a

I recently encountered a problem with my code that used to access the camera on Chrome browser and release it after use. Here's the code snippet: Starting the Camera: navigator.webkitGetUserMedia($scope.options.videoObj, function (stream) { $sco ...

Angular's Readonly component fails to display line breaks

I am currently developing an Angular application using C#. One issue I have encountered is with read-only components that display saved data from the database. For instance, when inputting text into a Textarea component, such as: hello there hello ...

dc.js bar graph bars blending together

This datetime barChart is causing me some trouble. Interestingly, when I try to replicate the issue in a fiddle (check here), everything functions as expected. Please note that the data takes about 30 seconds to load from github. Below is the code for the ...

GraphQL query excluding empty fields for various types of objects

Utilizing Apollo Graphql, I attempted to employ inheritance for retrieving various types of models without success. My goal is to extract specific fields from the objects while omitting those that are unnecessary. To address the issue of incomplete object ...

Is there a way to eliminate empty arrays from my data?

I'm dealing with this PHP code snippet. public function display_children($parent,$level){ try { $cmd = $this->connection->prepare('SELECT mem,pid from mytree where pid = ?'); $cmd->execute(array($parent)); ...

What is the process for converting the output of cryptoJS.sha256 to binary in a Postman pre-request script?

Seeking assistance in creating an HMAC signature using a pre-request script in Postman. While troubleshooting, it has become apparent that there is an issue with the signature generation process. Although a proof of concept example provides expected result ...

Click on the link or tab to update the marker location on the Google Map

Can you click on Tab 2 to change the marker/location, and then go back to Tab 1 to switch it back to the original location? [Links to Fiddle] http://jsfiddle.net/ye3x8/ function initialize() { var styles = [{ stylers: [{ saturati ...

Unexpectedly, the child component within the modal in React Native has been resetting to its default state

In my setup, there is a parent component called LeagueSelect and a child component known as TeamSelect. LeagueSelect functions as a React Native modal that can be adjusted accordingly. An interesting observation I've made is that when I open the Lea ...

When utilizing the app.get method, it allows for multiple arguments to be passed in. For example, the app.get('/', requireAuth, (req, res) => { }) function can be

I'm curious about the functionality of express.js when specifying multiple arguments in the app.get method, like this: app.get('/', requireAuth, (req, res) => { }) In this example, we have '/' as the route, (req, res) as argume ...

Exploring Angular14: A guide to efficiently looping through the controls of strictly typed FormGroups

Currently, I am working on upgrading my formGroups to be strictly typed in Angular v14. Within my FormGroup, there is a specific block of logic that iterates through all the controls and performs an action (this part is not crucial as I am facing issues be ...

Error: Trying to access properties of an undefined object (specifically 'promise.data.map')

Currently, I am in the process of writing unit tests for a project built with Angular version 1.2. For my controller tests, I have set up a mockService that returns a deferred promise. One of the service methods looks like this: function getItems() { ...

Error authorizing AJAX call to Gmail API

I'm just getting started with the GMail API and I'm attempting to use AJAX to fetch emails. This is my code: $.ajax({ beforeSend: function (request) { request.setRequestHeader("authorization", "Bearer xxxxxxxxxxxxxxxxx.a ...