简体   繁体   中英

How to include JS file in HTML, using NodeJS Express server?

I'm creating a chat, using server Express of NodeJS and AngularJS for manager in client side

But when I try include /js/code.js in my html , it can not found, because is not routed by Express

<!-- my include in html -->
<script src="./js/code.js"></script> <!- this is not found in execution -->

Meu index.js:

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

app.get('/', function(request, response){
    response.sendFile(__dirname + '/index.html');
});

How to can I fix this problem, without route all js file I will using in my project or routing all js file in path a lot?

Use app.use to specify your public files to your node app, like below

app.use(express.static(yourPublicPath));

EDIT:

You are getting "Express undefined" error because it is not defined. You can easily fix this by defining your app in 2 stages:-

var express = require('express');
var app = express();

On a side note, I would strongly recommend to go through Expressjs docs to learn more about Express.

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