Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

HTML to Node.js server POST request on localhost with Fetch

Excuse any wrong usage of terms or words, still trying to understand Node.js.

I am running a website with LiveServer and a Node.js server on the same PC. I realise I could be running the website as a Node.js app but I am trying to use POST with Fetch to send a file from the website to the server.

The server will handle file copying and maybe some other things that I find interesting but for now that’s it.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The problem is I can’t even connect to localhost. LiveServer is running on port 5501 and Node server on port 5000.

Below is the code for the index.js file for the website, it just takes a drag&drop event and tries to send the file to localhost:5000:

                var file = event.dataTransfer.items[i].getAsFile();
                console.log('... file[' + i + '].name = ' + file.name);

                var data = new FormData();
                data.append('file', file);

                const url = new URL('http://localhost:5000/');

                fetch(url, {
                    method:'POST',
                    body: data
                })
            }

And here is the Node.js server code:

const express = require('express'); //Import the express dependency
const cors = require('cors');

const app = express();              //Instantiate an express app, the main work horse of this server
const port = 5000;                  //Save the port number where your server will be listening

//setting middleware
app.use('/dist', express.static('dist'));

app.use(cors({
    allowedOrigins: [
        'http://localhost:5000'
    ]
}));

// //Idiomatic expression in express to route and respond to a client request
// app.get('/', (req, res) => {        //get requests to the root ("/") will route here
//     res.sendFile('src/index.html', { root: __dirname });      //server responds by sending the index.html file to the client's browser
//     //the .sendFile method needs the absolute path to the file, see: https://expressjs.com/en/4x/api.html#res.sendFile 
// });


app.listen(port, () => {            //server starts listening for any attempts from a client to connect at port: {port}
    console.log(`Now listening on port ${port}`);
});


app.post('http://localhost:5000/', function (req, res) {
    // const body = req.body.Body
    // res.set('Content-Type', 'text/plain')
    // res.send(`You sent: ${body} to Express`)
    res.sendFile('src/index.html', { root: __dirname });      //server responds by sending the index.html file to the client's browser

})

The error I get in Chrome is: POST http://localhost:5000/ 404 (Not Found)

Is what I am trying to do even possible? I’ve tried different variations of typing the URL and still I get the same error message. Google isn’t helpful either.

Any help is appreciated, thanks in advance.

>Solution :

First argument on the app.METHOD must be the path for which the middleware function is invoked; can be any of:

  1. A string representing a path.
  2. A path pattern.
  3. A regular expression pattern to match paths.
  4. An array of combinations of any of the above.

So therefore this line

app.post('http://localhost:5000/', ...)

has to be a pathname only, so replace it with this

app.post('/', ... )
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading