I cloned the http server with: git clone https://github.com/http-party/http-server
In a terminal I execute the command: node ./bin/http-server --username test --password image --cors
The http server is now running on http://localhost:8080 and I see the landing page successfully
When I go to http://localhost:8080/img/turtle.png then I am prompted for username and password.
When I enter test
and image
then I see the turtle successfully.
I have another app running on http://localhost:8081/ that does not promp for credentials when I use this:
<img alt="use-credentials"
src="http://localhost:8080/img/turtle.png"
crossOrigin="use-credentials">
but this image is not rendreing, instead I get the error:
Access to image at 'http://localhost:8080/img/turtle.png' from origin 'http://localhost:8081' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I have read all the articles, blogs, questions and watched the videos, but I cannot find a single working example on how to use crossorigin use-credentials, all the examples out there are using anonymous and explaining use-credentials very vaguely.
CodePudding user response:
To allow an image from one domain (e.g., http://localhost:8080) to be used on another domain (e.g., http://localhost:8081) with the use-credentials value for the crossOrigin attribute, the server hosting the image (http://localhost:8080 in this case) must include the Access-Control-Allow-Origin and Access-Control-Allow-Credentials headers in its response to requests for the image.
For example, if the server is running on Node.js, you could add these headers to the server's response like this:
app.get('/img/turtle.png', (req, res) => {
// Set the Access-Control-Allow-Origin and Access-Control-Allow-Credentials headers
res.set('Access-Control-Allow-Origin', 'http://localhost:8081');
res.set('Access-Control-Allow-Credentials', 'true');
// Serve the image
res.sendFile(path.join(__dirname, 'img', 'turtle.png'));
});
This tells the browser that it's OK for http://localhost:8081 to access the image at http://localhost:8080/img/turtle.png with credentials (i.e., with the user's login information).
Once the server is configured to include these headers in its response, the tag on the page at http://localhost:8081 can use the use-credentials value for the crossOrigin attribute to allow the image to be displayed:
<img alt="use-credentials"
src="http://localhost:8080/img/turtle.png"
crossOrigin="use-credentials">
With these changes in place, the image should be displayed on the page at http://localhost:8081 without any CORS errors.