简体   繁体   English

Node.js、Express.js 不向客户端发送文件

[英]Node.js, Express.js doesn't send file to client

I'm trying to send a gif to the client to use later in CSS.我正在尝试向客户端发送 gif 以供稍后在 CSS 中使用。 The console logs give me a 404 not found for the gif.控制台日志给我一个 404 not found for the gif。 It is in the public directory.它在公共目录中。

Server:服务器:

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var express = require('express');
var peopleCount = 0;


express().use(express.static('public'));

app.get('/', function(req, res){
    res.sendFile(__dirname + '/public/index.html');
  });

CSS CSS

span {
            background:url('public/gif.gif');
            background-repeat:repeat-x;
            background-position:0 0;
            text-align:center;
            color:transparent;
            -webkit-background-clip:text;
            -moz-background-clip:text;
            background-clip:text;
            -webkit-text-fill-color:transparent;
            font-weight: bold;
            font-size: 20px;
    }

The server sends the index.html file fine, but not the gif.gif服务器发送index.html文件很好,但不是gif.gif

try:尝试:

app.use(express.static('public'));

instead of代替

express().use(express.static('public'));

For starters, public/gif.gif is a relative reference, so this will look for the file at <window location>/public/gif.gif .对于初学者来说, public/gif.gif是一个相对引用,所以这将在<window location>/public/gif.gif查找文件。 Assuming you want this to reference the <root>/public/gif.gif , use an absolute reference (notice the leading / ):假设您希望它引用<root>/public/gif.gif ,请使用绝对引用(注意前导/ ):

background:url('/public/gif.gif');

In addition, the static directories should be bound to the app instance, and should specify a name to be used when calling to the server:此外,静态目录应绑定到应用程序实例,并应指定调用服务器时要使用的名称:

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

in the above example, the __dirname + /public directory in your project would be located at /public when making calls to the server.在上面的示例中,当调用服务器时,项目中的__dirname + /public目录将位于/public

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

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