URL获取时,节点Js Express静态文件失败

时间:2019-08-18 01:16:49

标签: node.js json

我是Node J的新手,并做一些练习示例。当发送获取请求作为URL ID时,静态文件无法正常运行。

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

    // It works. Static files loaded properly from http://localhost:3000/themify-icons.css
    app.get('/about', (req,res) => {
        res.render('about', {
            title: 'About'
        });
    });

    // It opens productdetail.ejs but Static files failed here. 
// When I check the 'css' from view page source, Its locating to http://localhost:3000/product/themify-icons.css
    app.get('/product/:id',(req,res) => {
        // console.log(req.params.id);

        res.render('productdetail', {
            title:'Product Details'
        });
    });
    app.listen(3000);

app('/product/:id')打开productdetail.ejs,但此处的静态文件失败。当我从查看页面源中检查“ css”时,其位置为http://localhost:3000/product/themify-icons.css

我了解其在路径中添加的“产品”。即使在此url id get方法中,我也该如何解决?

2 个答案:

答案 0 :(得分:1)

如果浏览器正在请求http://localhost:3000/product/themify-icons.css,但是您只希望它请求http://localhost:3000/themify-icons.css,则将标记中的url更改为前导/。因此,代替

"themify-icons.css"

使用:

"/themeify-icons.css" 

在您的<style>标签中。对于您不希望将页面URL的路径添加到其中的所有静态资源,都应该如此。

只有文件名时,浏览器将从页面URL中获取路径,并将其添加到文件名中。当您使用前导/时,浏览器仅从页面URL(而不是路径)获取协议,主机和端口。

答案 1 :(得分:0)

如果“公共”文件夹直接位于项目根目录中,请写入

app.use(express.static(path.join(__dirname, 'public')));

代替

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

从项目根目录获取正确的相对路径。
__dirname将引用执行当前脚本的文件夹。


注意:您需要使用“路径”模块:

let path = require('path');