所以我从这个 youtube 站点编写了完全显示的所有代码(以及基于我的计算机的所有正确路径 URL)教程:https://www.youtube.com/watch?v=NA21dUBfJhw&list=PL4cUxeGkcC9gcy9lrvMJ75z9maRw4byYp&index=33 (除了这个家伙懒得写 const http = require('http') 以及其他用于本地主机的东西,所以我将其添加到我的代码中。 下面是我的代码(与教程的代码+本地主机设置完全相同)
下面的代码是app.js
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
});
server.listen(port, hostname, () => {
console.log('Server running at http://${hostname}:#{port}/');
});
var express = require('express');
var todoController = require('./todoController');
var app = express();
app.set('view engine', 'ejs');
app.use(express.static('./'));
todoController(app);
下面的代码是todo.ejs
<html>
<head>
<title>Todo List</title>
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-
CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
<link href="/Public/styles.css" rel="stylesheet"
type="text/css">
</head>
<body>
<div id="todo-table">
<form>
<input type="text" name="item" placeholder="Add new
item..." require />
<button type="submit">Add Item</button>
</form>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</div>
</body>
</html>
下面的代码是todoController.js
module.exports = function(app) {
app.get('/todo', function(req, res){
res.render('todo');
});
app.post('/todo', function(req, res){
});
app.delete('/todo', function(req, res){
});
};
最佳答案
您创建了两台服务器,一台使用 http 模块,另一台使用 Express,但您只监听 http 服务器。
只需将“server.listen”函数移到todoController(app)之后,并将“server”更改为“app”,如下所示
app.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
在这种情况下,您的服务器将监听 Express。
关于node.js - 我完全按照教程所示编写了代码,但它不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56514584/