简体   繁体   English

Javascript 文件未加载到本地主机上

[英]Javascript file isn't loading on local host

I am just learning express and I tried to create a simple webpage on localhost:3000.我只是在学习 express,我尝试在 localhost:3000 上创建一个简单的网页。 I created a text box with a submit button, which on click will get the text element inside the text box and print it on the console.我创建了一个带有提交按钮的文本框,单击该按钮将获取文本框内的文本元素并将其打印在控制台上。

My node.js code is:我的 node.js 代码是:

const express = require('express')
const path = require('path')
const hbs = require('hbs')

const app=express();

app.set('view engine', 'hbs');
const dir= path.join(__dirname,'../templates/views');
const partials=path.join(__dirname,'../templates/partials')
app.set('views',dir);
hbs.registerPartials(partials);

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

app.listen(3000, () => {
    console.log(`Server started on port`);
});
 

The test.hbs file code is: test.hbs 文件代码为:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
     {{>header}}
    <form class="form">
        <input type="text" placeholder="Write here" class="textbox">
        <input type="submit" class="btn">
    </form>
    <script src="./test.js"></script>
</body>
</html>

And the javascript code is和 javascript 代码是

const values={
    nodeForm:document.querySelector('.form'),
    nodeText:document.querySelector('.textbox'),
    nodeBtn:document.querySelector('.btn')
}

values.nodeForm.addEventListener('submit',e=>{
    e.preventDefault();
    console.log(nodeText.value)
    
})

But when I open up the localhost:3000 , the console page gives me an error, saying GET http://localhost:3000/test.js net::ERR_ABORTED 404 (Not Found)但是当我打开localhost:3000 ,控制台页面给了我一个错误,说GET http://localhost:3000/test.js net::ERR_ABORTED 404 (Not Found)

Edit: Javascript works fine if I put scripts inside the script tag present in the test.hbs file编辑:如果我将脚本放在 test.hbs 文件中的脚本标签中,Javascript 工作正常

Once your html is going back to your navigator, it will load any ressources it needs (such as images, css or script).一旦您的 html 返回到您的导航器,它将加载它需要的任何资源(例如图像、css 或脚本)。 This is why you got a 404 error, it can't reach 'localhost/test.js'这就是为什么您收到 404 错误,它无法访问 'localhost/test.js'

So you have to put test.js available.所以你必须让 test.js 可用。

The common way is yo use a /public folder and put every static ressources in it.常用的方法是使用 /public 文件夹并将所有静态资源放入其中。

So where you have your node.js file, create a "public" folder因此,在您拥有 node.js 文件的地方,创建一个“public”文件夹

Put in it your test.js file.将您的 test.js 文件放入其中。

Add this in Node before your app.listen() :在你的 app.listen() 之前在 Node 中添加这个:

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

In HTML :在 HTML 中:

<script src="/static/test.js"></script>

'static' is the name you want for the public route 'public' is the name of the folder in your app 'static' 是您想要的公共路由名称 'public' 是您的应用程序中文件夹的名称

Of course you can change route and folder name as you wish.当然,您可以根据需要更改路线和文件夹名称。

And you can add subfolder to it.您可以向其中添加子文件夹。 For example put test.js in path app/public/js/test.js.例如将 test.js 放在路径 app/public/js/test.js 中。 And refer to it in HTML with src="/static/js/test.js"并在 HTML 中使用 src="/static/js/test.js" 引用它

Lets explain futher what is happening when you create a node server such as yours.让我们进一步解释当您创建像您这样的节点服务器时会发生什么。

When you start it (with app.listen() ) the server will listen for incoming request and return an awnser.当您启动它时(使用app.listen() ),服务器将侦听传入的请求并返回一个 awnser。

If you try to access 'localhost:3000/dumb' the navigator request your server asking him for '/dumb' route.如果您尝试访问 'localhost:3000/dumb',导航器会请求您的服务器向他询问 '/dumb' 路由。 As it dosn't exist, the server awnser a 404 error.由于它不存在,服务器 awnser 出现 404 错误。

If you now try to access 'localhost:3000/' the server find a route, execute your callback ( (req, res) => res.render('test') ) and in this callback you use Handlebar to generate an html page which is send to the navigator.如果您现在尝试访问 'localhost:3000/' 服务器会找到一个路由,执行您的回调( (req, res) => res.render('test') ),并在此回调中使用 Handlebar 生成一个 html 页面这是发送到导航器。

Then the navigator get the HTML, parse it and find several links (like <script src="./test.js"> but also <img href="./myimage.png"> or <stylesheet href="./style.css"> ) To be able to fully render the page, the navigator will request each link it found to get the associated ressources.然后导航器获取 HTML,解析它并找到几个链接(例如<script src="./test.js">以及<img href="./myimage.png"><stylesheet href="./style.css"> ) 为了能够完全呈现页面,导航器将请求它找到的每个链接以获取关联的资源。

So in your case the navigator send one more request to 'localhost:3000/test.js' and as in my first dumb example the server awnser that it doesn't know this route.因此,在您的情况下,导航器向 'localhost:3000/test.js' 再发送一个请求,就像在我的第一个愚蠢示例中一样,它不知道此路由的服务器 awnser。

You could create a route for each ressource ( app.get('./test.js', /*...*/) with a callback sending back the correct ressource. But as those file are just static (doesn't need any computation), the most common way to solve it is to make them available staticly. That means saying to your app "this folder is full of static file, juste serve them".您可以为每个资源创建一个路由( app.get('./test.js', /*...*/)并带有回调发送回正确的资源。但由于这些文件只是静态的(不需要任何计算),解决它的最常见方法是使它们静态可用。这意味着对您的应用程序说“此文件夹充满静态文件,请为它们提供服务”。

As i said you can just create a 'public' folder and tell your app it contains static files : app.use(express.static('./public'));正如我所说,您可以创建一个“公共”文件夹并告诉您的应用程序它包含静态文件: app.use(express.static('./public')); Of course './public' being a correct path from your root app (where package.json and node_modules is).当然,'./public' 是根应用程序(package.json 和 node_modules 所在的位置)的正确路径。

But then, every files and folders in this folder become a reachable route.但是,这个文件夹中的每个文件和文件夹都变成了一条可达的路径。 So if you have a 'js' folder in it, and later you want to create an app.get('/js', /*...*/) route you will have a conflict.所以如果你有一个 'js' 文件夹,然后你想创建一个app.get('/js', /*...*/)路由,你就会有冲突。

So the common way is to serve this folder under a route.所以常见的方法是在一个路由下服务这个文件夹。 For example app.use('/static', express.static('./public'));例如app.use('/static', express.static('./public')); will make everything under './public' folder available under '/static' routes.将使“./public”文件夹下的所有内容在“/static”路由下可用。 In your case 'localhost:3000/static/test.js'.在你的情况下'localhost:3000/static/test.js'。

I hope this is more clear, sorry for the poor english, this is not my native language.我希望这更清楚,抱歉英语不好,这不是我的母语。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM