'Link to multer saved image only working in local host
I've been trying to get multer to work on my node express API. It stores the file name all perfectly however when i try and open a link to view the image it will only work when trying this in local host.
Below is some code to explain further:
Here is the code for the API which i have on the server:
const express = require('express');
const app = express();
const multer = require("multer");
const path = require("path");
const db = require('./db');
const cors = require('cors');
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true , limit: '50mb'}));
app.use(cors());
const upload = multer({
storage: storage,
limits: {
fileSize: 100000
}
})
const storage = multer.diskStorage({
destination: './upload/images',
filename: (req, file, cb) => {
return cb(null, `${file.fieldname}_${Date.now()}${path.extname(file.originalname)}`)
}
})
app.use('/profile', express.static('upload/images'));
app.post("/marketplace-api/rest-api/upload", upload.single('profile'), (req, res) => {
res.json({
success: 1,
profile_url: `http://link to api/${req.file.filename}`
})
})
I've not included the link to my api in the profile_url as we can see. Below now is what my folder structure looks like in the api uploaded on the server:
The images get uploaded to the upload/images route
however when i try to open the link that i get when uploading an image in the profile_url part of the code i get this error :"Cannot GET /marketplace-api/rest-api/profile_1650449891984.jpg".
But once i try this on local host so i would only change the app.post so it works with local files i would change it to:
app.use('/profile', express.static('upload/images'));
app.post("/upload", upload.single('profile'), (req, res) => {
res.json({
success: 1,
profile_url: `http://localhost:4000/profile/${req.file.filename}`
})
})
The link would finally work. I have no idea why it's not working on the server. I've been trying to work this out for the past day or two. So if anyone could point me in the right direction it would be highly appreciated.
Thank You!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
