【发布时间】:2019-09-11 02:23:44
【问题描述】:
我正在尝试使用 <script> 标记将 javascript 文件链接到 html 文件。呈现 html 页面时,我在控制台中看到一个错误,声称找不到 javascript 文件。
下面是我的项目结构:
`
Volume serial number is 0E1E-EFCF
C:.
│ file.txt
│ README.md
│
├───html
│ charts.html
│
├───javascript
│ charts.js
│
└───Server
package-lock.json
package.json
server.js
`
我正在尝试通过在 charts.html 文件中执行以下操作将 charts.js 文件链接到 charts.html 文件:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<p id="paragraph">This is an example.</p>
<script src="/../javascript/charts.js"></script>
</body>
</html>
我正在使用 node.js 来渲染文件,而我的 server.js 文件包含了我所有的路由:
//jshint esversion:6
//'importing' express.
const express = require('express');
//importing bodyParser
const bodyParser = require('body-parser');
//importing the request package
const request = require('request');
//importing path for accessing directories in different levels.
var path = require('path');
//specifies that this app will be using express.
const app = express();
//Configure bodyParser before using.
app.use(bodyParser.urlencoded({extended:true}));
//static AWS EC2 instance server port. Edit with caution.
const serverPort = 5000;
//AWS EC2 instance Base URL for remote access.
const awsEc2InstanceBaseUrl
= "http://ec2-34-219-122-169.us-west-2.compute.amazonaws.com" + ":" + serverPort;
//Handle all root requests.
app.get("/", function(req, res) {
res.send("Hello, World!");
});
//THIS IS CAUSING ISSUE(?)
app.get("/charts", function(req, res) {
res.sendFile( path.resolve(__dirname + "/../html/charts.html"));
});
app.get("/test-api", function(req, res){
const testApiEndpoint = "https://www.googleapis.com/books/v1/volumes?q=isbn:0747532699";
//The following few lines documents how to make an API call using javascript
request(testApiEndpoint, function(error, response, body){
console.log(body);
res.sendFile(body);
});
});
//Start-up behaviour.
app.listen(serverPort, function() {
console.log("Server started on AWS EC2 instance: " + awsEc2InstanceBaseUrl);
console.log("You may access the server locally via: http://localhost:" + serverPort);
});
我假设 javascript 文件的路径是相对于 charts.html 文件的。但是鉴于我在渲染时看到 404 not found 错误,我想我错了。
Failed to load resource: the server responded with a status of 404 (Not Found)
我哪里错了?
【问题讨论】:
-
您提供的所有内容都没有显示您如何告诉服务器提供 js 或 html 文件。就像 apache、njinx 或其他任何用于提供文件的东西一样,您必须指定应该提供什么。
-
@KevinB : 如何告诉服务器如何提供 js 或 html 文件?
-
视情况而定。您目前如何提供 html 文件?通常......在生产中处理这种情况的方式是使用 apache 或 njinx 而不是 node.js 提供静态文件。但在开发过程中,通常使用 express 或任何您用来处理路由的方式为它们提供服务。
-
本地通过 node.js 和 chrome
-
所以我假设您有某种... res.sendFile 用于.html 文件?您需要为要提供的每个其他文件执行类似的操作,或者使用您用于提供整个文件夹的 api 可用的任何方法。
标签: javascript html node.js