Get 无法 GET / in NodeJS Express 项目



我已经尝试了许多方法来解决这个问题,从app.use(express.static(__dirname + "public"))res.render,它在我的终端中有效,但在我的本地主机中不起作用。我哪里出错了? 这是我的JS文件:

const express = require('express');
const bodyParser = require('body-parser');
var fs = require ('fs');
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
//
app.get('/index', function (req, res) {
res.sendFile( __dirname + "/" + "index.html" );
})
//app.use(express.static(__dirname + '/public'));
//app.get('/index.html', (request, response) =>  response.sendFile( __dirname, "/index.html"));
app.post('/userinfo', (request, response) => {
const postBody = request.body;
console.log(postBody);
response.send(postBody);
});
app.listen(3002, () => console.info('Application running on port 3002'));

这是我的 HTML 文件:

<!-- index.html -->
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Express - Node.js POST data example</title>
</head>
<body>
<form action="/userinfo" method="POST">
Some data: <input type="text" name="data" id="data">
<button type="submit">Send</button>
</form>
</body>
</html>

基本 url没有响应或定义了/路由。您只定义了两个路由,我假设您的索引页/index。因此,页面将在localhost:3002/index.您必须为/基本 url定义另一个响应,例如,

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

希望您的问题会得到解决。

最新更新