我在使用express提供静态javascript文件时遇到问题。我尝试了许多不同版本的快递文档无济于事。我还尝试过很多关于S / O类似问题的回复。
我的文件夹结构是
-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);
});
我试图通过localhost:4000 / foo.js访问foo.js,但我不断得到404错误。
任何帮助非常感谢
答案 0 :(得分:0)
在原始帖子上查看来自@MysterX的评论。您的目录不正确。
app.use(express.static(path.join(__dirname, 'public')));
应该是
app.use(express.static(path.join(__dirname, 'server/public')));