How to load static images on ExpressJs - mysql

so I have this node/express api that serve MySQL database, has json output like this:
[
{
id: 1,
name: "Laptop Lenovo",
serial: "123-456",
tag: "IT-CL-22052018-001",
image: "/public/images/lenovo.jpg"
},
{
id: 2,
name: "Desktop Dell",
serial: "456-123",
tag: "IT.CD.19052018-002",
image: "public/images/dell.jpg"
},
{
id: 3,
name: "Laptop Dell",
serial: "909090",
tag: "IT.CL.01052018.002",
image: "http://localhost:8000/images/ldell.jpg"
}
]
I tried this express functions each one of it:
app.use(express.static('public'))
app.use('/static', express.static('public'))
var dir = path.join(__dirname, 'public');
app.use(express.static(dir));
And the only way my React app can display the image is by using the full url on the database, like #3.
How I can display the image without using the full url?
Edit: Add Render Function
render() {
return this.state.inventory.map(itemList => {
let item = itemList;
return (
// <div className="tile">
<div className="card margin-all">
<div className="card-content">
<div className="media">
<div>
<figure className="image is-96x96">
<img src={item.image} />
</figure>
</div>
</div>
<div>
<h4>Nama: {item.name} </h4>
<h4>Nomor Seri: {item.serial} </h4>
<h4>ID Tag: {item.tag} </h4>
</div>
</div>
</div>
// </div>
);
})
}
}
Pict

For express middleware app.use(express.static('public')) is fine, problem is you need to use correct path. In you json data, image is public/images/dell.jpg which should be /public/images/dell.jpg but you can use
<img src={ '/' + item.image} />
as well, hope this will help

The route for static assets is /static/ so I assume you must call the images like this (e.g. #2)
app.use('/static', express.static('public'))
But you're requesting it via /public/
{
id: 2,
name: "Desktop Dell",
serial: "456-123",
tag: "IT.CD.19052018-002",
image: "static/images/dell.jpg"
}
So if you want the path from your origin JSON get working change it to
app.use('/public', express.static(__dirname + '/public'));
From express.js documentation:
http://expressjs.com/en/starter/static-files.html
However, the path that you provide to the express.static function is relative to the directory from where you launch your node process. If you run the express app from another directory, it’s safer to use the absolute path of the directory that you want to serve

So by adding a proxy to React app, I don't need to provide full url to the link.
If the express port is 8000, then put this line in the package.json of the React App, not the Node app.
"proxy": "http://localhost:8000"
Now I can use images/name.jpg and the image will be displayed.

Related

Uncaught Error: Cannot find module 'file:/home/agemiro/backend-gerenciador/uploads/imagemteste.png'

I'm using React JS and I'm having trouble accessing an image that comes from a state/variable. If I put the url inside the require in the html img it works but when it comes from outside it doesn't work at all. I wish someone would clarify this because it's been four days since I've been trying to find out. Important: This url I'm using comes from outside the React application
const [sideDishesImage, setSideDishesImage] = useState([
{
fileName: "",
id: "",
message: "",
sideId: "",
url: "file:/home/agemiro/backend-gerenciador/uploads/imagemteste.png"
}
]);
<img {require(`${sideDishesImage[0].url}`)} alt="image" />
You have two ways to reference an asset in a create-react-app app:
path to the asset, the asset has to be placed in the public folder, and you can reference it like:
const url = "/images/myImage.png" // myImage.png must be inside "public/images"
<img src={url} alt="alt" />
Load the asset through webpack:
import img from "path/to/the/asset.png" // This can be outside of public folder but must be inside the /src folder
<img src={img} alt="alt" />

how to attach image using v-for in vue 3

im trying to make a set of images using v-for loop, but somehow it doesn't recognise variables inside the tag. pic is broken and alt just shows me {{ item.alt }} thing.
Here is my HTML:
<section class="our-technologies__section" v-for="(item, index) in tech_item" :key="index">
<div class="technologies__logo" #click="activeIndex = index" :class="{active: activeIndex === index}">
<img src="{{ item.src }}" alt="{{ item.alt }}">
<p>{{item.title}}</p>
</div>
</section>
And here are script:
export default {
name: "OurTechnologies",
data: function () {
return{
tech_item: [
{ title: 'Twilio', text: 'gfmds/lgkmlk/f', src: '../../images/twilio.png', alt: 'Twilio' },
{ title: 'Android', text: '12334356676', src: '../../images/android.png', alt: 'Android' },
],
activeIndex: 0,
}
},
}
I tried to use <img :src="item.src" :alt="item.alt"> and its still no results.
In vue cli you should use require to load the image :
<img :src="require(item.src)" :alt="item.alt"/>
<img :src="item.src" :alt="item.alt"> should work ™, but then I don't know enough about the environment you have set up. I quickly tried with a fresh project using vite and using the App component (so that it was root level), it didn't even need require for it to work. For this to work your images would be usually be in the ./src/assets/ directory, which they are not and I'm wondering if that's what is causing the problems, that the images are falling out of scope. You likely have a different setup, but I think you might able to use another option.
Place the images into the ./public/images/ folder. This will make them included as part of the bundle whether you're using dev/serve or build. Then reference them as /images/*.png without require or import. As long as you are serving the app at root level so that /images resolves correctly this should make it work. Otherwise it may need a bit of extra finessing to target the right directory.

why the html content not shown out when running

Now i use visual studio code to do my project. I can build my code without error, but when running, it no show out the content for html file, only have show css like header abd footer. i have click button on header but cannot go to other page.Here is the sample code
code in index.html
<nav>
List
New student
Student feedback
</nav>
Vue router
const router = new VueRouter({
routes: [
{ path: '/home', component: load('home') },
{ path: '/insert', component: load('insert') },
{ path: '/update/:id', component: load('update') },
{ path: '/feedback', component: load('feedback') },
{ path: '*', redirect: '/home' }
]
});
File name and type: _home.html, _insert.html, _update.html, _feedback.html
Can help me see the problem, thank you
I don't think you should edit directly to index.html as Vue is Single Page Application (SPA) framework. Instead, you should use Vue Component for each page.
This video might help you to figure out how to use Vue and Vue Router properly: https://youtu.be/nnVVOe7qdeQ
Edit:
For sake of clarity, Let me build simplified diagram of Vue project for you.
First of all, make sure you create the project via vue cli. It guides you to build your new vue project better.
Let's say we have 3 pages:
Home
About
Another
Each page has its own CSS, HTML (we call it template), and JavaScript in one file, the .vue file. To connect them, we need a first entrance, main.js. Inside of it, we can configure the router.
Inside main.js
import Vue from "vue";
import VueRouter from "vue-router";
import App from "./App.vue";
import HomePage from "./HomePage.vue";
import AboutPage from "./AboutPage.vue";
import AnotherPage from "./AnotherPage.vue";
// This is your router configuration
Vue.use(VueRouter);
const router = new VueRouter({
[
{ path: "/", component: HomePage },
{ path: "/about", component: AboutPage },
{ path: "/another", component: AnotherPage },
],
mode: "history",
});
// Initialize Vue App
new Vue({
router,
render: h => h(App),
}).$mount("#app");
Then, we need to create App.vue and put <router-view /> inside of it.
Inside App.vue source file
<template>
<div id="app">
<router-view />
</div>
</template>
<script>
export default {
// Keep this empty. Except if you
// need to add sidebar or any else.
}
</script>
Now you're ready to create those three pages
Every pages looks like this:
<style scoped>
// Your CSS here
</style>
<template>
<div>
<!-- Your HTML here -->
</div>
</template>
<script>
export default {
data() {
return {
// Your reactive data here
}
},
mounted() {
// Your script here
},
methods: {
// Your functions here
},
}
</script>
That's all I can explain, hope it helps. If I missed something, please don't hesitate to tell me. Thank you!

Nuxt JS 500 error when refreshing page loaded using JSON

I'm having a weird problem with my Nuxt JS website. I have created a system which uses Vue Resource and URL parameters to fetch JSON data to build a page, the idea is that it will eventually be controlled via a backend/API.
The problem I'm facing, is the pages work absolutely fine when in development mode running npm run dev, however, in production mode they break and cause a 500 internal server error when refreshing the page. But they don't break when loading the homepage and then navigating to page. (the homepage is a .vue file).
I'm not sure where to even begin with this problem. This is my page which essentially pulls data from a JSON file which is currently held locally, and each page is a JSON file right now. It works fine in development mode though.
<template>
<div class="page-json">
<pageBanner v-bind:bannerTitle="banner.bannerTitle" v-bind:bannerSubTitle="page.bannerSubTitle" v-bind:subTitleEnabled="page.bannerHasSubTitle" v-bind:bgClass="banner.bgClass" />
<section class="py-4 py-md-5">
<div class="container">
<div class="row py-4 py-md-5">
<div class="col-lg-4 col-md-4 col-sm-12">
<SearchComponent v-bind:orientationMargin="search.hasMargin" v-bind:searchPosition="search.orientation" v-bind:componentClass="search.searchClass" />
</div>
<div class="col-lg-8 col-md-8 col-sm-12 page-content">
<div v-html="page.content"></div>
<Alert v-bind:hasClass="errors.api.hasClass" v-bind:hasError="errors.api.hasError" v-bind:message="errors.api.message" v-bind:icon="errors.api.icon" />
</div>
</div>
</div>
</section>
</div>
</template>
<script>
import pageBanner from '~/components/PageBanner.vue'
import SearchComponent from '~/components/SearchComponent.vue'
import Alert from '~/components/Alert.vue'
export default {
components: {
pageBanner,
SearchComponent,
Alert
},
data () {
return {
slug: this.$route.params.slug,
page: [],
banner: {
bannerTitle: 'Page',
bgClass: 'jumbotron-houses jumbotron-page'
},
search: {
searchClass: 'mb-4 mb-md-0',
hasMargin: 'mb-3',
orientation: 'd-block'
},
errors: {
api: {
hasError: false,
hasClass: 'alert-danger mt-3 mt-md-0',
message: 'We was unable to fetch you property data.',
icon: 'error'
}
}
}
},
created() {
this.$http.get('/pages/' + this.slug + '.json').then(response => {
this.page = response.body
}, response => {
// this.$router.push('/404')
});
},
head () {
return {
title: this.page.pageTitle + ' | Site',
meta: [
{ hid: 'description', name: 'description', content: this.page.pageDescription + ' - Site' }
]
}
}
}
</script>
Not entirely sure why it causes an internal server error when refreshing the page or visiting the page directly.
Can anyone help?
UPDATE:
Could this be because of a missing .htaccess file / rewrites? In production mode there is no .htaccess file for the dist folder?
This is my Apache error log:
[Tue Sep 25 11:51:39 2018] [error] [client ::1] Request exceeded the limit of 10 internal redirects due to probable configuration error. Use 'LimitInternalRecursion' to increase the limit if necessary. Use 'LogLevel debug' to get a backtrace., referer: http://property-boilerplate.ryan/testimonials

Vue - i am trying to display an image from a url from an array but the image is not displaying

this is one of my first projects with vue.
Basically, I am trying to display an image from a URL from an array.
On the webpage, the URL is in the image back but the actual image is not displaying.
This is in my main vue class
<div id="painting">
<ul v-if="artwork && artwork.length">
<li v-for='(artworks, index) in artwork' :key='index'>
<img v-bind:src="artworks.thumbnailUrl" />
</li>
</ul>
<router-view/>
</div>
then the script code:
<script>
import axios from 'axios';
export default {
data() {
return {
artwork: []
}
},
created() {
axios.get(`http://localhost:9000/artwork`)
.then(response => {
this.artwork = response.data;
})
.catch(e => {
this.errors.push(e)
})
}
}
</script>
This is what it looks like on the web, the url is there but no picture
I have declared a width and a height of the image as well with css
I should mention i getting the information from the database in a node project and connecting by a port number
I am pretty new to stack so I would love any feedback, cheers
From you screenshot code, this looks fine. I can see the image by writing similar HTML
<li>
<img data-v-xcxcc src="http://www.tate.org.uk/art/images/work/A/A00/A00007_8.jpg" />
</li>
https://jsfiddle.net/y2m75usk/
Try clearing your cache or reload the page by Holding the Ctrl key and press the F5 key.
Thanks!