Reputation:
I have a create form that is working, however, my images don't seem to be uploading to S3 due to CORS
I get the following
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://henrywatches-dev.s3.amazonaws.com/. (Reason: CORS header 'Access-Control-Allow-Origin' missing).
I have the following fetch
request
if (isValid) {
fetch("/api/collections/create", {
method: "POST",
mode: "cors",
body: JSON.stringify(this.state),
headers: {
Accept: "application/json",
"Content-Type": "application/json"
}
})
.then(res => res.json())
.then(() => uploadFile(this.state.images, this.s3Config))
.then(
() => this.setState({ successMsg: true }),
() => this.setState(initalState)
)
.catch(error => {
console.log(error);
});
}
Like I mentioned the form is working and a record does get created, it's just S3 .then(() => uploadFile(this.state.images, this.s3Config))
that is being blocked. I have setup cors using express but as S3 is happening in the front-end cors pops up again as it's not happening server-side.
I've tried mode: 'cors'
but that doesn't do anything in terms of fixing the error.
Upvotes: 0
Views: 1306
Reputation: 809
You need to set these headers on your back-end:
'Access-Control-Allow-Origin'
with value '*'
'Access-Control-Allow-Headers'
with value '*'
'Access-Control-Allow-Methods'
with value 'GET, POST, PUT, DELETE,
OPTIONS'This will get rid of the error.
But how to actually set the headers?
There is at least one middleware on npm for handling CORS in Express: cors.
This is how to set custom response headers, from the ExpressJS DOC
res.set(field, [value])
Set header field to value
res.set('Content-Type', 'text/plain');
or pass an object to set multiple fields at once.
res.set({
'Content-Type': 'text/plain',
'Content-Length': '123',
'ETag': '12345'
})
Aliased as
res.header(field, [value])
Upvotes: 1