[英]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"
. 这适用于我的AWS Elastic beantalk,但是,当我使用nodejs http-server
时,出现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) 在控制台node server.js
(在server.js具有您发布的代码)上像这样运行
Did you double check the PORT env variable when you start the server? 启动服务器时是否仔细检查了PORT env变量? If you didn't set PORT env variable, make sure to go to http://localhost:8080/ on browser. 如果未设置PORT env变量,请确保在浏览器上转到http:// localhost:8080 / 。 To check env variables on console, you can execute the command env
要在控制台上检查env变量,可以执行命令env
Do you have an index.html so that html = fs.readFileSync('index.html');
您是否有一个index.html,以便html = fs.readFileSync('index.html');
works? 作品?
You should not use http-server
for this, you should use plain node.js: 您不应为此使用http-server
,而应使用普通的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 Http-server用于服务未由节点执行的文件,但是很明显,您已经编写了一个脚本,节点应执行该脚本以返回响应
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.