When I link javascript file in html it sends a request to server and causing error

后端 未结 3 1560
不知归路
不知归路 2020-12-22 05:35

I am using express and node.js in backend and ejs templating engine in front-end. My app.js look like this

app.get(\'/book/:id\', (req, res)=>{
var book_i         


        
相关标签:
3条回答
  • 2020-12-22 06:06

    I think that your book.ejs file is under the route of '/book'. if that so, you script tag like <script type="text/javascript" src="books.js"></script> will access the route of /book/book.js ,not your assets. so you should set you src attribute like this /book.js and make sure you had made your assets accessible.

    0 讨论(0)
  • 2020-12-22 06:09

    Since script links have relative paths, they are loaded from current path, which is /book.

    They should either have absolute paths:

    <script type="text/javascript" src="/jquery-3.3.1.min.js"></script>
    <script type="text/javascript" src="/books.js"></script>
    

    Or base URL should be specified:

    <base href="/">
    
    0 讨论(0)
  • 2020-12-22 06:10

    You are using relative path in src attribute. Since you are serving the page from /books/<id>, if you use a relative path, browser will understand it as /books/(relative_path_of_resource) and so when it comes across those links it is sending a request to books/jquery.js and books/books.js

    You should convert your link to point to the correct static path of the js files. Refer this link - https://expressjs.com/en/starter/static-files.html to see how to serve static files and once you set up the serving, you can change the links to /static/books.js and /static/jquery.js

    0 讨论(0)
提交回复
热议问题