[英]Nodejs: can't get /
I'm trying to write a simple web page. 我正在尝试编写一个简单的网页。 It's based on 2 html and a index.js.
它基于2个html和一个index.js。 I'm using nodejs and express for routing.
我正在使用nodejs并表达路由。 When I launch with
当我启动
node index.js
节点index.js
it seems to work fine, until I get to the browser and go to 似乎工作正常,直到我进入浏览器并转到
localhost:8080/
本地主机:8080 /
then the browser tells me 然后浏览器告诉我
cannot get /
不能获取 /
No error is displayed in the terminal nor in the console of both Firefox and Chrome. Firefox和Chrome的终端或控制台中均未显示任何错误。
Here is the code: 这是代码:
index.js index.js
var express=require('express');
var app=express();
app.use(express.static(__dirname+'/public'));
app.get("/", function(req, res){
res.sendFile(__dirname+"main.html");
});
app.get("/choice/:choice/travel/:travel/name/:name", function(req, res){
res.sendFile("result.html", {
choice : req.params.choice,
travel : req.params.travel,
name : req.params.name
});
});
express().listen((process.env.PORT || 8080), function(){
console.log("Server running at: "+(process.env.PORT || 8080));
});
main.html main.html
<!DOCTYPE html>
<html>
<head>
<title>Survey Norway</title>
</head>
<body>
<h1>Survey Norway</h1>
<p>The survey is anonymous unless you insert your name<p>
<h2>Would you come to Norway this summer?</h2>
<form action="">
<input type="radio" name="choice" value="1" onclick="showMore()">Yes<br>
<input type="radio" name="choice" value="0" onclick="hide()">No
</form>
<div id="mytext" style="display: none;">
<h2>Which one would you choose?</h2>
<form action="">
<input type="radio" name="travel" value="1">Rent a car and travel Europe<br>
<input type="radio" name="travel" value="2">Fly. <br>
<input type="radio" name="travel" value="0">Doesn't matter.
</form>
</div>
<p>If you want insert yor name here:.</p>
<input type="text" name="name">
<center>
<button onclick="send_()">Send</button>
</center>
</body>
</html>
<script type="text/javascript">
function showMore (){
document.getElementById("mytext").style.display="block";
}
function hide (){
document.getElementById("mytext").style.display="none";
}
function send_(){
var choice=document.querySelector('input[name = "choice"]:checked').value;
var viaggio=0;
if (choice==1){
viaggio=document.querySelector('input[name = "travel"]:checked').value;
}
var nome=document.querySelector('input[name = "name"]').value;
console.log("choice: "+choice+"\ntravel: "+travel+"\nname: "+name);
}
</script>
Can anyone tell me what I'm doing wrong? 谁能告诉我我在做什么错?
Change this: 更改此:
express().listen(...)
to this: 对此:
app.listen(...)
You were making a new express instance and listening with that one and that's a different instance than the one you put your routes on. 您正在创建一个新的Express实例,并监听该实例,这与您放置路线的实例不同。 So, the server you actually created and started had no routes defined on it.
因此,您实际创建和启动的服务器上没有定义任何路由。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.