Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

I uploaded image to the server, but failed to bring images #1954

Open
yonghunJ opened this issue Jul 9, 2019 · 8 comments
Open

I uploaded image to the server, but failed to bring images #1954

yonghunJ opened this issue Jul 9, 2019 · 8 comments

Comments

@yonghunJ
Copy link

yonghunJ commented Jul 9, 2019

-mean
-----server
--------- config
-------------config.js
-------- controllers
-------- data
-------- images <---I saved images here using "multer "package

I added this line in mean/server/config/config,js

  • app.use('images', express.static(path.join(__dirname,'/../images')))

When I try to access a static image from the browser=>localhost:4040/images
it gives me 401 Unauthorized error.

I don't know why it does not work.
Could you please able to give me an advice?

@evolmk
Copy link

evolmk commented Jul 9, 2019

I haven't used this project myself, but it has helped me learn some new angular features (i came from AngularJS), i can probably help.

  1. I'd recommend you move your app.use middleware code to inside /server/config/express.js file where other similar statements are. (near line 30, before or after the other ones)

  2. Adjust your app.use middleware code, from express's docs: "the path that you provide to the express.static function is relative to the directory from where you launch your node process" Which i believe node's "root" process of this app is server/index.js. I am unsure of the Node Process root, so you try some of examples i provided

So if your folder is /server/images, try the following (but read tutorial below) and adjust it. like docs say, path you specify is relative to the node process.

app.use('/images', express.static(path.join(__dirname, 'images')))
or
app.use('/images', express.static(path.join(__dirname, './images')))
or
app.use('/images', express.static(path.join(__dirname, '../images')))

  • you should be able to fetch your image from localhost:4040/images/FILENAME.jpg
  • of course, make sure that file exists in that /server/images folder first!!

Full Guide from Express.js on serving static files, very useful:
https://expressjs.com/en/starter/static-files.html

Happy MEAN'ing

@yonghunJ
Copy link
Author

yonghunJ commented Jul 9, 2019

Thank you guys,

I moved this code in the express.js and tried those code with localhost:4040/images/haha.jpg which exsits in images folder.
app.use('/images', express.static(path.join(__dirname, 'images')))
app.use('/images', express.static(path.join(__dirname, '/images')))
app.use('/images', express.static(path.join(__dirname, './images')))
app.use('/images', express.static(path.join(__dirname, '../images')))
app.use('/images', express.static(path.join(__dirname, '/../images')))

but I was not able to get any image.
In my opinion, app.use('/images', express.static(path.join(__dirname, '/../images')))
this code is right, because __dirname give me "Y:\vmv\mean\server\config"
Do you have other idea about it?
Thank you so much in advance

@evolmk
Copy link

evolmk commented Jul 10, 2019

and you restarted app? otherwise one of those tests should have worked. Sorry i'm still learning how Angular 7+ builds/compiles app, i'm from Angular 1 world and that should have worked.

If you can't get the express path to work, and get 401, might be something to configure with the /angular.json file. Sorry i'm not much more help, hopefully someone else can chime in, goodluck!

@yonghunJ
Copy link
Author

Because I am using Nodemon, it automatically restarts the server after saving the file.
I tried another way.
after downloading recent mean stack files again and request the URL for an image from the node server, but the result is same.. even though one of the other my mean stack works well which is not based on this template.

Thank you so much for your help.
I appreciate it

@mkshverma
Copy link

Hi,
Do not add your code in config.js
app.use('images', express.static(path.join(__dirname,'../images')))
add this line in express.js before the line containing app.use(
then you can access the images on /images

@hackman01
Copy link

Hello,
I am able to access the image in browser(via image url) but i am getting CORP error while fetching from react (axios).
Please help me to solve this one

@mkshverma
Copy link

You have to use cors library if frontend and backend have different url.

@LolwaBro
Copy link

LolwaBro commented Jan 18, 2025

I encountered similar problem in my project. When I enter full url of the image in the browser, it would load. But when I try to load in <img src="http://localhost:8000/uploads/example.png"> I would get a CORS error in the console.

Here is how I solved it:

  1. Install cors from npm. In the server root file, in my case it is index.js, I used:
const cors = require("cors");
app.use(
    cors({
        origin: FRONTEND_URL, // "http://localhost:3000" or "http://example.com"  or "https://example.com" 
        methods: "GET,POST,PUT,DELETE",
        credentials: true,
    })
);

app.use("/uploads", express.static(path.join(__dirname, "uploads")));
  1. In the frontend, make sure you include crossOrigin="use-credentials" attribute for <audio>, <img>, <link>, <script>, and <video> elements. E.g. <img src="http://localhost:8000/uploads/example.png" crossOrigin="use-credentials">

I found the solution after reading the mdn docs; link - https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/crossorigin

I think the problem might have arisen because I have included credentials: true in my cors configuration. Hence I need to specify crossOrigin="use-credentials".

Edit:

If you don't want to use crossOrigin attribute, then set credentials: false in the cors configuration.

The following snippet will resolve most of your cors issues and handle preflight requests and It doesn't require any extra library. Modify it as per your requirements.

app.use(function (req, res, next) {
    // Allow api access only to these request origins
    const allowedOrigins = [
        "http://localhost:3000",
        process.env.CLIENT_URL,
        // otherUrls
    ];
    const origin = req.headers.origin;

    // Check if the request is coming from our allowed origins
    if (allowedOrigins.includes(origin)) {
        res.header("Access-Control-Allow-Origin", origin); 
        res.header(
            "Access-Control-Allow-Headers",
            "Origin, X-Requested-With, Content-Type, Accept, Authorization"
        );
        res.header(
            "Access-Control-Allow-Methods",
            "GET, POST, PUT, DELETE, OPTIONS"
        );
        res.header("Access-Control-Allow-Credentials", "true");
    }

    if (req.method === "OPTIONS") {
        return res.sendStatus(204); // Handle preflight
    }

    next();
});

Something I discovered:
For testing, you can also add the ipv4 address of the device on which you are hosting your app along with the port in the allowedOrigins array. This will allow you to access your website from any device that is connected to your wifi network.

For e.g. Lets say I start my web app on http://localhost:3000. I find out my ipv4 address, suppose 192.168.2.2. My new web app address then becomes http://192.168.2.2:3000. I then add it in my allowed origins list.

const allowedOrigins = [
    "http://localhost:3000",
    "http://192.168.2.2:3000",
];

Now when I search http://192.168.2.2:3000 from the browser of the other device that is connected to the same wifi network, it loads up my localhost website. This allowed me to test my web app in mobile devices.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants