Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
671 views
in Technique[技术] by (71.8m points)

node.js - Script path for ExpressJS in node_modules

I have an index.jade in my 'views' folder.

doctype html
html
  head
    title= title
    link(rel='stylesheet', href='/stylesheets/main.css')
    script(src='../node_modules/some_package/package_script.min.js')

I have index.js in my routes folder with a router:

router.get('/', function(req, res) {
  res.render('index', { title: 'title goes here' })
});

I keep getting a 404 error when I try to access the node_modules folder in the jade file in the console: GET /node_modules/some_package/package_script.min.js 404 1ms - 19b

How exactly does the file pathing work / how can I fix it for Express when I'm trying to access a script in the node_modules? Do I need to copy the necessary javascript files and place them under the 'javascripts' folder under 'public' for it to work?

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Whoa! Hold on... node_modules is a private directory and shouldn't be exposed. By default the public directory is the public root path for static files:

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

In there is a javascripts directory. Copy your script there and change the src attribute in your template to:

/javascripts/package_script.min.js

If you really wanted to serve up node_modules, which would be a bad idea, add the following beneath the app.use(express.static(...)); line above:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...