[英]Express (Node.js) - Include CSS and JS files conditionally
[英]include css and JavaScript file on node express
我想在node-express中包含我的css文件和javascript文件,但始终找不到404:这是我的代码:1.在server.js中
var http = require('http');
var app = require('./app');
var express = require('express');
var apps = express();
var path = require('path');
apps.use(express.static(path.join(__dirname, 'public')));
http.createServer(app.handleRequest).listen(8000);
然后在app.js上
var url = require('url');
var fs = require('fs');
function renderHTML(path, response) {
response.writeHead(200, { 'Content-Type': 'text/html' });
fs.readFile(path, null, function(error, data) {
if (error) {
response.writeHead(404);
response.write('File not found!');
} else {
response.write(data);
}
response.end();
});
}
和我的路线仍在app.js上:
module.exports = {
handleRequest: function(request, response) {
var path = url.parse(request.url).pathname;
switch (path) {
case '/':
renderHTML('./index.html', response);
break;
case '/login':
renderHTML('./login.html', response);
break;
default:
response.writeHead(404);
response.write('Route not defined');
response.end();
}
}
};
这是我的html:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test Doc</title>
<link rel="stylesheet" type="text/css" href="/css/style.css" />
</head>
<body>
<p>Coba ku </p>
<div id="container" style="height: 500px"></div>
</body>
</html>
我使用vs代码来构建它。
我很困惑。 您使用express处理静态文件,但是为什么要创建没有express的本机节点服务器,express无法正常工作。
更改您的server.js
var app = require('./app');
var express = require('express');
var apps = express();
var path = require('path');
apps.use(express.static(path.join(__dirname, 'public')));
apps.use(app.handleRequest);
apps.listen(8000);
了解官方文档app.listen()以了解其外观。
无需创建诸如renderHTML
类的功能即可提供HTML。
// Instead of this:
renderHTML('./index.html', response);
// Just use that:
response.sendFile(path.join(__dirname, '../public', 'index.html'));
// or (the same):
response.sendFile('index.html', { root: path.join(__dirname, '../public') });
您可以在此处找到更多信息res.sendFile() 。
我不得不说,有一种更好的方法来实现您通过app.handleRequest()
函数中的switch
实现的路由。 路由
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.