简体   繁体   English

express.static不提供

[英]express.static does not deliver

I searched through all topics, but could not find a similar issue. 我搜索了所有主题,但是找不到类似的问题。

I have a server.js in the folder /build 我在/build文件夹中有一个server.js

// /build/server.js

import express from 'express';

const app = express();

app.use('/static', express.static(path.join(__dirname, 'build', 'static'), { maxAge: '30d' }));

and a css file in /build/static/css/my.css . /build/static/css/my.css的css文件。 I start nodemon with build/server.js from the root folder / 我从根文件夹/build/server.js启动nodemon

I assume that I should get my file via localhost:8080/static/css/my.css But it returns a 404 and "Cannot GET /static/css/my.css" 我假设我应该通过localhost:8080 / static / css / my.css获取文件,但它返回404和“无法获取/static/css/my.css”

What could be the issue? 可能是什么问题? I tried a lot of different paths, but never got a successful response. 我尝试了许多不同的途径,但从未获得成功的回应。

Thanks in advance. 提前致谢。

I finally decided to go with __dirname to prevent errors caused by relative paths to the directory the server is started from. 我最终决定使用__dirname来防止由于服务器启动目录的相对路径引起的错误。

The main problem was that __dirname always returned / . 主要问题是__dirname总是返回/ I added the following lines to my webpack config: 我在webpack配置中添加了以下几行:

target: 'node', // was already there
node: { // has been added
  __filename: false,
  __dirname: false
},

You can find a closer description of this behaviour of __dirname in webpack here: https://github.com/webpack/webpack/issues/2010#issuecomment-181256611 您可以在以下位置找到有关webpack中__dirname行为的详细描述: https : //github.com/webpack/webpack/issues/2010#issuecomment-181256611

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM