簡體   English   中英

具有Localhost的簡單NodeJS Server,錯誤(404):“未找到”

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

這是針對允許交叉來源的測試環境配置。 這適用於我的AWS Elastic beantalk,但是,當我使用nodejs http-server時,出現Error (404): "Not found" 我嘗試了不同的配置。 另外,我發現的許多與此問題相關的答案都涉及速成,但我並未使用。 如果有人知道或看到我在做什么錯,我將非常感謝您的幫助。 謝謝高級!

   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);

它對我在本地主機上正常工作

  • 在控制台node server.js (在server.js具有您發布的代碼)上像這樣運行

  • 啟動服務器時是否仔細檢查了PORT env變量? 如果未設置PORT env變量,請確保在瀏覽器上轉到http:// localhost:8080 / 要在控制台上檢查env變量,可以執行命令env

  • 您是否有一個index.html,以便html = fs.readFileSync('index.html'); 作品?

您不應為此使用http-server ,而應使用普通的node.js:

node yourfile.js

Http-server用於服務未由節點執行的文件,但是很明顯,您已經編寫了一個腳本,節點應執行該腳本以返回響應

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM