简体   繁体   中英

Simple NodeJS Server with Localhost, Error (404): “Not found”

This is for a test environment configuration that allows for cross origin. This works with my AWS elastic beanstalk however, when I use the nodejs http-server , I am getting Error (404): "Not found" . I have tried different configurations. Also, many of the answers I found related to this issue deal with express, which I am not using. If anyone knows or sees what I am doing wrong, I would greatly appreciate the help. Thank you in advanced!

   var port = process.env.PORT || 8080,
        http = require('http'),
        fs = require('fs'),
        html = fs.readFileSync('index.html');
    var server = http.createServer(function(req, res) {
        res.setHeader('Access-Control-Allow-Origin', '*');
        res.setHeader('Access-Control-Request-Method', '*');
        res.setHeader('Access-Control-Allow-Methods', 'OPTIONS,GET,PUT,POST,DELETE');
        res.setHeader('Access-Control-Allow-Headers', '*');

        if (req.method === 'POST') {
            var body = '';

            req.on('data', function(chunk) {
                body += chunk;
            });

            req.on('end', function() {
                if (req.url === '/') {
                    log('Received message: ' + body);
                } else if (req.url = '/scheduled') {
                    log('Received task ' + req.headers['x-aws-sqsd-taskname'] + ' scheduled at ' + req.headers['x-aws-sqsd-scheduled-at']);
                }

                res.writeHead(200, 'OK', { 'Content-Type': 'text/plain' });
                var ip = req.connection.remoteAddress
                res.write(body);
                res.end();
            });
        } else {
            res.writeHead(200);
            res.write(html);
            res.end();
        }
    });
    server.listen(port);

It works just fine for me on localhost

  • Run like this on console node server.js (where server.js has the code you posted)

  • Did you double check the PORT env variable when you start the server? If you didn't set PORT env variable, make sure to go to http://localhost:8080/ on browser. To check env variables on console, you can execute the command env

  • Do you have an index.html so that html = fs.readFileSync('index.html'); works?

You should not use http-server for this, you should use plain node.js:

node yourfile.js

Http-server is meant for serving files that are not executed by node, but it is evident that you have written a script that node should execute to return the response

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM