WABBIT0111
WABBIT0111

Reputation: 2313

nodejs how to serve node_modules directory to front end for access?

Without using any packaging software such as Browserify or Webpack, I have a simple server that in nodejs.

var express = require('express');
var bodyParser = require('body-parser');
var request = require('request');
var app = express();
app.use(bodyParser());
app.use(express.static('public'));
app.use(express.static('node_modules'));


app.post('/api/searchjob', function (req, res) {
  res.json({data: "hello"});
});

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

app.get('/*', function(req, res){
  res.redirect('/');
})

app.listen(process.env.PORT || 3000, function () {
  console.log('Example app listening on port 3000!')
});

I want the front end to also have access to some node_modules packages, what can i do? my index.html file is in "public" directory, the folder structure look like this:

├── README.md
├── index.js
├── node_modules
├── package.json
├── public
└── yarn.lock

I tried simply put the script tag in index.html, but doesn't work <script src="../node_modules/vue2-google-maps/dist/vue-google-maps.js"></script>

Upvotes: 8

Views: 3893

Answers (2)

MWY
MWY

Reputation: 1181

I write this:

  app.use(express.static(path.join(__dirname, 'node_modules')));
  <script src="/vue2-google-maps/dist/vue-google-maps.js"></script>

Upvotes: 2

Patrick Hund
Patrick Hund

Reputation: 20266

You are already using the express static middleware to serve files from your node_modules directory, so a path like this should work:

<script src="/vue2-google-maps/dist/vue-google-maps.js"></script>

Upvotes: 4

Related Questions