daedbliati daedbliati - 1 year ago 83
Javascript Question

Browser loading html in js file (node.js)

Apologies for the confusing title, the confusing title is a byproduct of my own confusion.

I am working with Node.js to write a web server and an api. Everything was going well, until I ran into this problem. Here is my server/api code:

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});

Here is test.html:

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

here is test.js:

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

Now test.html does everything as expected if I open the file with a browser. However, if I run the server and navigate to , I get the following error:

Uncaught SyntaxError: Unexpected token <

Confused, I checked under "Sources" in Chrome devtools, and despite Chrome saying that it's loading "test.js" the code that it's running as "test.js" is identical to that of "test.html". Does anyone know why this is happening?

I used an identical method in order to deliver html/css/js in my other rest calls in the same file, and all of those pages are working as intended.

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

That doesn't make sense.

Every time you get a request for /profile/:url you try to set up the static plugin, then you return the contents of test.html.

When the browser asks for /profile/test.js that code … returns the contents of test.html.

Presumably you are planning to put some dynamic code in there to generate the profile page dynamically. That means you should not put the JS under `/profile/ because it isn't a profile page.


Configure the static plugin properly:

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


Point the URL at the right place:

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

Note the . is removed so you are accessing from the root instead of from the current path segment.