我是使用Node的新手,我正在尝试制作一个简单的HTML页面,它可以在本地获取图像、样式表和脚本。每次我尝试加载本地文件时,它都会返回404状态。我尝试了StackOverflow和其他来源的多种解决方案,但仍然不能正常工作。
下面是我在app.js中的代码:
const app = require('express')();
const http = require('http').createServer(app);
var portNumber = 8085;
app.get('/', function(reg, res) {
res.sendFile(__dirname + '/index.html');
});
http.listen(portNumber, function() {
console.log('Listening on port ' + portNumber);
});
我在public > stylesheets > style.css中有一个CSS文件链接到我的HTML文档。
<link rel="stylesheet" type="text/css" href="public/stylesheets/style.css" />
我在浏览器的控制台中得到了一个404错误。我还收到了一个MIME错误:来自“http://localhost:8085/public/stylesheets/style.css”的资源由于MIME类型(“文本/html”)不匹配(X-Content- type -Options: nosniff)而被阻塞。
我试图加载的任何本地图像也会给出一个404错误。
我曾尝试添加app.use(express.static('public'));
以使公共文件夹成为提供静态内容的根目录,如Express documentation所示,但我仍然收到了404个错误。
const express = require('express');
const app = express();
const http = require('http').createServer(app);
var portNumber = 8085;
app.use(express.static('public'));
app.get('/', function(reg, res) {
res.sendFile(__dirname + '/index.html');
});
http.listen(portNumber, function() {
console.log('Listening on port ' + portNumber);
});
我不知道我应该做什么。我想要的是能够在我的HTML文档中加载本地文件。如何让这些文件公开显示,而不是给出404错误?
发布于 2019-11-23 00:17:10
mime错误的原因实际上是令人困惑的-它是由于浏览器无法找到该文件。
删除路径位置的/public
部分,因为它是文件夹,因此它是从以下位置提供的:
<link rel="stylesheet" type="text/css" href="/stylesheets/style.css" />
对于所有其他静态文件也是如此:/assets/mypic.png
等
按如下方式更新静态路径的位置:
app.use(express.static(path.join(__dirname, 'public'), {index: false}));
然后,将sendFile更新为use和absolute
路径,如下所示:
return res.sendfile(path.resolve('./index.html'));
// or
return res.sendfile(path.join(__dirname, 'index.html'));
发布于 2019-11-23 00:09:19
您应该尝试使用
app.use(express.static(__dirname + "/public"));
这样express就知道在哪里搜索public
文件夹。
https://stackoverflow.com/questions/59002726
复制