简体   繁体   中英

How to send browser content like Images, CSS and JS using Node, Express to html over browser?

Working on a project and trying to use nodejs and express to consume an API. Having issues though displaying the information.

When opened the index.html file directly with a browser, it displays perfectly. But when tried to do so with node and express , get the following:

链接到节点显示的图像并表达

server.js :

 var Access_token = 'ACCESS_TOKEN'; var AirTable = require('airtable'); var base = new AirTable({apiKey:Access_token}).base('BASE'); var TableName = 'TABLE_NAME'; var ViewName = 'Grid view'; var express = require('express'); var app = express(); app.get('/', function(request, response){ console.log(__dirname); response.sendFile(__dirname + '/index.html'); }); var listener = app.listen(process.env.PORT || '3000', function(){ console.log("Your app is listening to port " + listener.address().port); }); 

This is what my files' directory looks like 文件树

What is happening and what should I do? It clearly shows the index.html but it never pulls the css , scripts , or images .

You have to let Express know that requests to a specific URL will be for static assets in the respective folder, and not to try and route it itself. Add these lines before your listener:

app.use(express.static('css'));
app.use(express.static('fonts'));
app.use(express.static('img'));
app.use(express.static('js'));

Docs: Serving static files in Express

You might want to move towards single-page application as project grows or on learning new things.

use this in your server.js this will help you in multiple ways in long run.

const path  = require('path');

// Setup views directory, file type and public filder.
app.set('views', __dirname + '/views');

// ejs is just like html, stands for Embedded JavaScript templates. 
app.set('view engine', 'ejs');

// This will allow all your files in public folder available on browser.
// Files like JS, CSS, and Images
app.use(express.static(path.join(__dirname, 'public')));

app.get('/', (req, res) => {
    res.render('login');
});

Folder structure:

1. public
├─ 1. css
|  ├─ 1. app.css
|  ├─ 2. bootstrap.min.css
|  └─ 3. jquery-modal.min.css
├─ 2. js
|  ├─ 1. app.js
|  ├─ 2. jquery-modal.min.js
|  └─ 3. jquery.min.js
└─ 3. logo.jpg
2. views
├─ 1. index.ejs
└─ 2. login.ejs
6. .gitignore
7. app.js
8. package.lock.json
9. package.json

All ejs are just HTML with .ejs as extension in place of .html .

adding to esqew answer, you should move all static files inside a folter (eg public) and implement app.use:

app.use('static', express.static(__dirname + '/public'));

from your code you reference it with static and in the file system the folder's name is "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