how to access assets/images from the view in Sails.js?

非 Y 不嫁゛ 提交于 2019-12-10 03:12:24

问题


I simply want to add an image in a view in my Sails-Project

My view-file has the location

views/album/albums.ejs

and the image is located in

assets/images/placeholder.png

if I add the image like this

<img src="../../assets/images/placeholder.png">

I get this error

GET    http://localhost:1337/assets/images/placeholder.png    404 (Not Found)

Am I missing something?


回答1:


Sails use Grunt (Gruntfile.js in root of project) to execute some tasks during sails lift. One of that tasks is to copy files from assets directory to .tmp/public/ directory (in development version). So if u add your file to assets directory you will need to restart sails (sails lift) to get it accessible from .tmp/public/ (what is public accessible directory root). Also its important to note that if u put files directly to .tmp/public/ it will be accessible instant, but on next sails lift it will be deleted, since one of Grunt tasks is to clear that directory before copy new files. All of this u can find on sails documentation (assets and asset-management) and by reading Gruntfile.js in root of your project




回答2:


<img src="/images/placeholder.png">

should work. the assets folder is the equivalent to adding a folder with the static middleware in express.

asset documentation




回答3:


Looks like you have grunt hook removed.

When removing the grunt hook you must also specify the following in .sailsrc in order for your assets to be served, otherwise all assets will return a 404.

{
  "paths": {
    "public": "assets"
  }
}



回答4:


I was also facing the same problem.
In sails version 0.12.0,
I was trying to show an image from assets folder to homepage.ejs.
Then by using below img tag, it solved my problem.

<img src="/images/placeholder.png" width="30px" height="30px">

But as your ejs file is inside views/album/albums.ejs

I may suggest, below may work

<img src="../images/placeholder.png" width="30px" height="30px">

But the right approach in sails ejs pages is,

<img src="/images/placeholder.png" width="30px" height="30px">

This must work for you also.




回答5:


If you have the tasks/sync.js file in your project, add the following object in files array:

{
        cwd: './assets/images',
        src: ['**/*.*'],
        dest: '.tmp/public/images'
}

you need to have sails-hook-grunt and grunt-sync installed.



来源:https://stackoverflow.com/questions/18786136/how-to-access-assets-images-from-the-view-in-sails-js

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!