Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS file doesn't link with Pug

Tags:

javascript

pug

Can't link my js file to my pug browser console shows

The script from “http://localhost:3000/script.js” was loaded even though its MIME type (“text/html”) is not a valid JavaScript MIME type.
2 signin
Loading failed for the <script> with source “http://localhost:3000/script.js”. signin:1:1

I've tried doing this with script tags but my js code has some errors I guess and I can't see those errors unless the code is in a different file.

this is my pug file

script(type='text/javascript' src="http://code.jquery.com/jquery-latest.js")
script( type= 'text/javascript',src="./script.js")


form( id='formSignIn')
    div.form-group
      label(for='name') Id:
      input#name.form-control(type='text', placeholder='id' name='name')
    div.form-group
      label(for='pw') Password:
      input#password.form-control(type='password', name='password')
      button.btn.btn-primary(type='submit', id='submit') Sign In

this is my js file

$(document).ready(function(){
    console.log("hi");

        var name,password;
        // $("#submit").click(function(){
            name= $("#name").val();
            password=$("#password").val();
            console.log("$$$$$$$$$$$$$", name, password)
            $.post("/login", {name: name, password: password} ,function(data){
                console.log("AJAx");
            });
            console.log("@@@@@@@@@@@@@@@@@");
            localStorage.setItem('user',name);
    }
like image 466
bigdaddy-zephyr Avatar asked Sep 13 '25 09:09

bigdaddy-zephyr


1 Answers

Where is your index.js file (or app.js whatever your main server file is called)?

You need to set up your public folder, and put your script.js file in there.

EXAMPLE index.js file (or your main file that you are running as your server)

const express = require('express')
const path = require('path')
const app = express()    
const PORT = process.env.PORT || 3001
// static folder
app.use(express.static('public'))
// load view engine
// app.set('views', path.join(__dirname, 'view'))
app.set('view engine', 'pug')
// listening
app.listen(PORT, console.log(`Server started on port ${PORT}`))

You see the app.use(express.static('public')) line? This set your server to use your public folder. You create a public folder in your root folder. Put your script.js file in that public folder.

Now in your pug file, you can load your script.js file in there with the tag script(src='/script.js')

You DONT need to set it as '/public/script.js' BECAUSE you already set your public folder as the source. You just need to point to the file, which is just it's just '/script.js'

like image 121
Nhon Ha Avatar answered Sep 16 '25 01:09

Nhon Ha