Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/40.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 获取URL时节点Js Express静态文件失败_Node.js_Json - Fatal编程技术网

Node.js 获取URL时节点Js Express静态文件失败

Node.js 获取URL时节点Js Express静态文件失败,node.js,json,Node.js,Json,我是NodeJS新手,正在做一些实践示例。当以url id发送get请求时,静态文件无法正常工作 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', {

我是NodeJS新手,正在做一些实践示例。当以url id发送get请求时,静态文件无法正常工作

    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方法中,我如何解决这个问题?

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

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

app.use(express.static('public'));
从项目根获取正确的相对路径
\uuu dirname
将引用当前脚本执行所在的文件夹


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


如果浏览器正在请求
http://localhost:3000/product/themify-icons.css
,但您希望它只请求
http://localhost:3000/themify-icons.css,然后更改标记中的url,使其具有前导的
/
。因此,与其

"themify-icons.css"
使用:

标记中。对于您不希望将页面URL中的路径添加到的所有静态资源,这应该是正确的


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

不起作用
/home/user/Node/sprroject/views/productdetail.ejs/home/user/Node/sprroject/views/about.ejs/home/user/Node/sprroject/public/css/main.css
sprroject文件夹中的所有内容。
"themify-icons.css"
"/themeify-icons.css"