简体   繁体   English

如何从express中的同一目录访问静态文件?

[英]how to access static file from same directory in express?

i am trying to access the static file from the same directory but it is not working problem is it isn't loading the image in the live server我试图从同一目录访问静态文件,但它没有工作问题是它没有在实时服务器中加载图像

app.use('/static',express.static('/public'))

Here public is the main directory where I creat 'css'& 'img' folder and put my 'js' and 'html'file.这里 public 是我创建 'css' 和 'img' 文件夹并放置我的 'js' 和 'html' 文件的主目录。 Before I used to access the file out side of the same directory from where I creat a css and img folder & inside those folder I creat a 'css' file and put a image .在我以前从创建 css 和 img 文件夹的同一目录外访问文件之前,在这些文件夹中,我创建了一个“css”文件并放置了一个图像。 on that time it was working properly but when I put my 'js' and 'html' in the same directory where I creat my 'css' and 'img' folder it is not working means server is creating but in the 'HTML' file the 'image' is not loading in the live server.当时它工作正常,但是当我将“js”和“html”放在创建“css”和“img”文件夹的同一目录中时,它不起作用意味着服务器正在创建,但在“HTML”文件中“图像”未加载到实时服务器中。 hear is the code:听到的是代码:

const express= require('express')
const app= express()
app.use('/static',express.static('/public'))

app.set('view','./public/view')
app.get('/',(req,res)=>{
    res.send('user  accessed')
    
})
app.listen(5000,()=>{
     console.log("server is running at 5000")
})

Firstly, if you want to hear right answer you need to provide as more as possible information about your problem.首先,如果你想听到正确的答案,你需要提供尽可能多的关于你的问题的信息。 For example, you need to provide at least folder structure of your app, files which you want to include to your app and paths which you use.例如,您至少需要提供应用的文件夹结构、要包含到应用中的文件以及使用的路径。 And another point for you, why not to use best-practice solution which suggested by node js express creators?还有一点,为什么不使用 node js express 创建者建议的最佳实践解决方案? Here is express app generator https://expressjs.com/en/starter/generator.html .这是快速应用程序生成器https://expressjs.com/en/starter/generator.html If you keep to use the best practice solution then you will not have such questions.如果您继续使用最佳实践解决方案,那么您将不会遇到此类问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM