[英]nodejs response HTML file that contain script tag with src attribute
I want to send a html file that contain js file path.我想发送一个包含 js 文件路径的 html 文件。 This html file is in below.
这个 html 文件在下面。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple login</title>
</head>
<body>
<form id="main">
<input id="id" name="id" type="text" placeholder="ID"/> <br>
<input id="passwd" name="passwd" type="password" placeholder="password"/> <br>
<input type="submit" value="login" id="login">
</form>
<script src="./index_func.js"></script>
</body>
</html>
When I send this HTML file via express server index_func.js occurs 404 not found error当我通过快递服务器发送此 HTML 文件时 index_func.js 发生 404 not found 错误
And This is a router to send html file这是路由器发送html文件
const express = require('express');
const path = require('path');
const router = express.Router();
router.use(express.urlencoded({extended: true}));
router.post('/', (req, res, next) => {
try{
res.sendFile(path.join(__dirname, '../views/login.html'));
}
catch(err){
console.log(err);
next(err);
}
})
module.exports = router;
How can I resolve this problem?我该如何解决这个问题?
You will need to add static routing in your express project.您需要在 express 项目中添加 static 路由。
Create a folder public
in your project and put index_func.js
inside it.在您的项目中创建一个
public
文件夹并将index_func.js
放入其中。 Then add express.static('public')
as a route middleware.然后添加
express.static('public')
作为路由中间件。
Something like this -像这样的东西-
const express = require('express');
const path = require('path');
const router = express.Router();
router.use(express.urlencoded({extended: true}));
router.use(express.static('public'));
router.post('/', (req, res, next) => {
try{
res.sendFile(path.join(__dirname, '../views/login.html'));
}
catch(err){
console.log(err);
next(err);
}
})
module.exports = router;
Further reading - https://expressjs.com/en/starter/static-files.html进一步阅读 - https://expressjs.com/en/starter/static-files.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.