gpt4 book ai didi

javascript - Node.js/Express 错误 : cannot GET/

转载 作者:行者123 更新时间:2023-12-03 03:24:32 28 4
gpt4 key购买 nike

所以我有一些代码(app.js,在服务器中)

console.log("Server started. If you're reading this then your computer is still alive."); //Unnecessary test command to make sure everything works.

var express = require("express");
var app = express();
var serv = require("http").Server(app);

app.get("/", function(req, res) {
res.sendFile(__dirname + "/client");
});

app.use("/client", express.static(__dirname + "/client"));

serv.listen(2000);

//Set up server stuff. This isn't touched.

var io = require("socket.io")(serv, {});
io.sockets.on("connection", function(socket) {
console.log("Socket connection"); //This will print to the server, not the developer console in your browser.
});

//Initialize sockets and set up socket listeners. This isn't touched either, except when adding new events.

还有一些代码:

<!DOCTYPE html>
<html>
<head>
<title>Multiplayer!</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
</head>
<body>

<script>
var socket = io();
</script>

</body>
</html>

我的文件夹结构是:

multiplayer_game  
app.js
package.json
node_modules (folder)
node stuff
client (folder)
index.html
js (folder)
img (folder)
server (folder)

文件中的位置越远,它的“嵌套”程度就越高。
当我通过执行 node app.js (文件夹已 cd'ed)打开页面并转到 localhost:2000 时,我收到“Cannot GET/”。当我访问 localhost:2000/client 时,一切正常。我可以做什么来修复我的代码?

最佳答案

为此,您需要一个路由器。

const router = express.Router;
router.get('/', function(req, res) {
res.sendFile(__dirname + "/client");
});
app.use('/', router);

中间件无法处理各种http方法。

关于javascript - Node.js/Express 错误 : cannot GET/,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46393943/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com