繁体   English   中英

浏览器在js文件中加载html(node.js)

[英]Browser loading html in js file (node.js)

对于令人困惑的标题道歉,令人困惑的标题是我自己混淆的副产品。

我正在使用Node.js编写Web服务器和api。 一切都很顺利,直到遇到这个问题。 这是我的服务器/ api代码:

const express = require('express');
const app = express();
const port = 9001;
const bodyParser = require('body-parser');
const mysql = require('mysql');

app.get('/profile/:url', (request, response) =>{
  app.use('/profile/:url', express.static(__dirname+'/static_pages'));
  response.sendFile('static_pages/test.html', {root: __dirname});
});

这是test.html:

<!DOCTYPE html>
<html lang= "en">
  <head>
    <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
    <script type="text/javascript" src="./test.js"></script>
  </head>
  <body>
    <div class="test">test</div>
  </body>
</html>

这是test.js:

console.log('i run correctly!');

现在,如果我用浏览器打开文件,test.html会按预期执行所有操作。 但是,如果我运行服务器并导航到127.0.0.1:9001/profile/XXXXX,我会收到以下错误:

Uncaught SyntaxError: Unexpected token <

很困惑,我在Chrome devtools的“Sources”下查看,尽管Chrome说它正在加载“test.js”,但它运行的代码“test.js”与“test.html”的代码相同。 有谁知道为什么会这样?

我使用了一个相同的方法,以便在同一个文件中的其他休息调用中传递html / css / js,并且所有这些页面都按预期工作。

app.get('/profile/:url', (request, response) =>{
  app.use('/profile/:url', express.static(__dirname+'/static_pages'));
  response.sendFile('static_pages/test.html', {root: __dirname});
});

这没有意义。

每次收到/profile/:url的请求时,您都会尝试设置静态插件,然后返回test.html的内容。

当浏览器要求/profile/test.js代码时...返回test.html的内容。

据推测,您计划在其中放置一些动态代码以动态生成配置文件页面。 这意味着你不应该把JS放在`/ profile /下,因为它不是个人资料页面。

所以:

正确配置静态插件:

app.get('/ profile /:url',(request,response)=> {response.sendFile('static_pages / test.html',{root:__dirname});});

app.use(express.static(__目录名+ '/ static_pages'));

将URL指向正确的位置:

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

请注意. 已删除,因此您从根目录而不是从当前路径段访问。

暂无
暂无

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

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