how express forming the img URL

后端 未结 1 912
陌清茗
陌清茗 2021-01-28 19:41

I have created a simple node solution which contains a form and on that submit the form it will display the image that is being inserted in the form.

app.js

相关标签:
1条回答
  • 2021-01-28 20:15

    This is just how browser's handle relative paths.

    You have a Handlebars template that contains the following: <img src="{{file}}" class="responsive-img">

    The value of file is set to uploads/${req.file.filename}, which becomes something like uploads/myImage-1589223958713.PNG.

    When your template is executed with above value for file you get: <img src="uploads/myImage-1589223958713.PNG" class="responsive-img">

    When the browser sees a relative URL, like uploads/myImage-1589223958713.PNG, it has to figure out the absolute URL. Since this relative URL does not begin with a /, the browser thinks it is a child path of the current page URL.

    If the current page URL is http://localhost:3000/uploaded/uploader, the browser thinks your uploads/myImage-1589223958713.PNG URL is a child of http://localhost:3000/uploader/ and so produces: http://localhost:3000/uploader/uploads/myImage-1589223958713.PNG.

    To get the correct URL, you want to set the value for file so that it includes the full path:

    file: `/uploads/${req.file.filename}`
    

    Update: Note that /public should not be used included in the value for file because the /public directory is registered with express as a directory in which to look for static assets.

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