jrichalot
jrichalot

Reputation: 59

405 (Method not allowed) error returned upon POST request in node.js and express

I am testing a POST request using fetch() method and consistently get a 405 (Method not allowed) error. I am using express 4.17.1 and node 12.13.1 LTS

I have tested it on a "real machine" and a virtual machine with the same results. Both server and clients are on the same machine.

The server (index.js) is as follows:

// import the express library
const express = require('express');

// create an app object that inherits the library 
const app = express();

// get the app to listen
// the listen() function takes a port number and a callback function as arguments
app.listen(3000, () => console.log('listening on port 3000'));
// define the app root directory for static files
app.use(express.static('public'));

// set up a route to /api via the POST method
app.post('/api', (request,response)=>{
    console.log(request);
});

The client (index.html) is as follows:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <script>
        if ('geolocation' in navigator){
            console.log('geolocation available');
            navigator.geolocation.getCurrentPosition(position => {
                const lat = position.coords.latitude;
                const lon = position.coords.longitude;

                document.getElementById('latitude').textContent = lat;
                document.getElementById('longitude').textContent = lon;

                const data = {lat,lon};

                const options = {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                        },
                    body: JSON.stringify(data)
                 };

                 fetch('/api',options);

                });
        } else {
            console.log('geolocation unavailable')
        }

    </script>
    <h1>The selfie app</h1>
    <p>Latitude: <span id='latitude'></span>&deg;<br>
    longitude: <span id='longitude'></span>&deg;</p>
</body>
</html>

the root directory of the web application is "public". "/api" is a subdirectory of public (though I have also tried with "/api" being a directory on the same level as "public", to no avail).

I have tried the body-parser and allow-methods libraries with no succes.

I would very much appreciate if anyone had an explanation as to what is happening.

Upvotes: 1

Views: 8871

Answers (1)

jrichalot
jrichalot

Reputation: 59

Double-check port(s)

Check logs on both ends to confirm the correct port(s) are being used.

@Dijkstra above confirmed my code worked. That led me to look at my workflow. The culprit was the VSC extension live-server that I was using. It changes/translates the port my app is listening to (3000) in my case, to a default port (5500). This can be adjusted in the setting.json of the extension. I preferred to cut live-server out.

Upvotes: 1

Related Questions