简体   繁体   English

表达静态文件服务配置

[英]express static file serve configuration

I'm trying to serve static assets from express server which also happens to have Apollo Server installed on it, but this is an issue related to the express.static configuration. 我正在尝试从Express服务器提供静态资产,该服务器也恰好安装了Apollo Server,但这是与express.static配置相关的问题。 Here's a screenshot of my folder structure 这是我的文件夹结构的屏幕截图 在此处输入图片说明

Here's the code for express configuration. 这是快速配置的代码。 It lies inside /config/app.js 它位于/config/app.js

import express from 'express';
import bodyParser from 'body-parser';
import morgan from 'morgan';
import cookieParser from 'cookie-parser';
import cors from 'cors';
import path from 'path';

const PORT = process.env.PORT || 3001;
const environment = process.env.NODE_ENV || 'development';
const loggingType = environment === 'development' ? 'dev' : 'tiny';

const app = express();
app.use(
  bodyParser.json({ limit: 1024 * 1024 * 2000, type: 'application/json' })
);
app.use(morgan(loggingType));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, './assets/images')));

export default app;

If i try to access, localhost:3001/images, it says Cannot get /images 如果我尝试访问localhost:3001 / images,它说Cannot get /images

What am I doing wrong? 我究竟做错了什么?

Please try the following: 请尝试以下操作:

app.use(‘/assets’, express.static(path.join(__dirname, '..', ‘assets’)));

Change the parameters to path.join as per your directory structure. 根据您的目录结构将参数更改为path.join

__dirname represents the directory name of the current module. __dirname表示当前模块的目录名称。 You should use '../assets/images' as a static path for your images. 您应该使用“ ../assets/images”作为图像的静态路径。

Trying to access localhost:3001/images returns an error because it is a static directory, not a file. 尝试访问localhost:3001 / images会返回错误,因为它是静态目录,而不是文件。 Accessing localhost:3001/images/test.png should work. 访问localhost:3001 / images / test.png应该可以。

But first, you need to define your static directory. 但是首先,您需要定义您的静态目录。 Instead of : 代替 :

app.use(express.static(path.join(__dirname, './assets/images')));

do : 做:

app.use('/images', express.static(path.join(__dirname, '..', '/assets/images');

Hope this helps! 希望这可以帮助!

EDIT : changed __dirname target directory to correct one. 编辑:更改__dirname目标目录以更正其中一个。

You can use the static function in another way: 您可以通过其他方式使用static函数:

app.use('/', express.static('assets'));

...and call the image as the example below: ...并按以下示例调用图片:

<img src='/images/logo.png'>

I hope this helps. 我希望这有帮助。

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

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