简体   繁体   中英

Express not serving static files

I'm having an issue serving static javascript files using express. I've tried many different variations of the express documentation to no avail.I've also tried many of the responses to similar questions on S/O.

My folder structure is

-MyApp
 -client
 -server
   -public
    foo.js
  server.js

server.js:

require('rootpath')();
var express = require('express');
var app = express();
var cors = require('cors');
var bodyParser = require('body-parser');
var expressJwt = require('express-jwt');
var config = require('config.json');
var path = require('path');

app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

// use JWT auth to secure the api, the token can be passed in the authorization header or querystring
app.use(expressJwt({
    secret: config.secret,
    getToken: function (req) {
        if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') {
            return req.headers.authorization.split(' ')[1];
        } else if (req.query && req.query.token) {
            return req.query.token;
        }
        return null;
    }
}).unless({ path: ['/users/authenticate', '/users/register'] }));
// serve static files
app.use(express.static(path.join(__dirname, 'public')));
// routes
app.use('/users', require('./controllers/users.controller'));
app.use('/listings', require('./controllers/listings.controller'));

// start server
var port = process.env.NODE_ENV === 'production' ? 80 : 4000;
var server = app.listen(port, function () {
    console.log('Server listening on port ' + port);
});

I am trying to access foo.js through localhost:4000/foo.js but im getting 404 errors constantly.

Any help greatly appreciated

See comment from @MysterX on original post. Your directory in incorrect.

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

Should be

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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