我已经将我的代码简化为我可以做的最简单的express-js应用程序:

var express = require("express"),
    app = express.createServer();
app.use(express.static(__dirname + '/styles'));
app.listen(3001);

我的目录是这样的:

static_file.js
/styles
  default.css

然而,当我访问http://localhost:3001/styles/default.css时,我得到以下错误:

Cannot GET / styles /
default.css

我使用express 2.3.3和节点0.4.7。我做错了什么?


当前回答

我只是尝试这个代码和工作

const exp = require('express');
const app = exp();

app.use(exp.static("public"));

和工作,

工作前(未工作):

const express = require('express');
const app = express();
app.use(express.static("public"));

试试

其他回答

静态目录

检查上面的图像(静态目录)的目录结构

const publicDirectoryPath = path.join(__dirname,'../public')
app.use(express.static(publicDirectoryPath))


//  or

app.use("/", express.static(publicDirectoryPath))
app.use((req, res, next) => {
res.sendFile(path.join(publicDirectoryPath,'index.html'))

试试http://localhost: 3001 / default。

要在请求URL中使用/styles,请使用:

app.use("/styles", express.static(__dirname + '/styles'));

请看本页上的例子:

//Serve static content for the app from the "public" directory in the application directory.

    // GET /style.css etc
    app.use(express.static(__dirname + '/public'));

// Mount the middleware at "/static" to serve static content only when their request path is prefixed with "/static".

    // GET /static/style.css etc.
    app.use('/static', express.static(__dirname + '/public'));

提供__dirname的问题是__dirname返回当前文件的路径,而不是项目的文件。 此外,如果使用动态头文件,每个页面将在不同的路径中查找静态文件,这将不起作用。 对我来说,最好的方法是用__dirname代替process.cwd(),它总是将路径捐赠给项目文件。

app.use(express.static(process.cwd() + '/public'));

在你的项目中:

link rel="stylesheet" href="/styles/default.css"

参见:process.cwd()与__dirname之间的区别是什么?

我只是尝试这个代码和工作

const exp = require('express');
const app = exp();

app.use(exp.static("public"));

和工作,

工作前(未工作):

const express = require('express');
const app = express();
app.use(express.static("public"));

试试

除此之外,确保静态文件路径以/ (ex…/资产/ css)……在主目录(/main)之上的任何目录中提供静态文件