I use Symfony 5 and React, with docker.
Both container are on different docker-compose but on the same newtork, so they can see and ping each other.
Now I want to POST something on one of my api route, here is my request:
const handleSubmit = async function (e) {
setError(null)
setLoading(true)
e.preventDefault()
const data = new FormData(e.target)
console.warn(data)
try {
const response = await fetch('https://localhost:8443/authentication_token', {
credentials: 'include',
headers: {
Accept: 'application/json',
},
method: 'POST',
body: data,
})
console.warn(response)
const responseData = await response.json()
console.warn(responseData)
onConnect(responseData)
} catch (e) {
setError(e)
setLoading(false)
}
}
Then I'm getting the following error:
Access to fetch at 'https://localhost:8443/authentication_token' from origin 'http://localhost:3001' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
So after some search I installed nelmio package to deal with cors, here is my nelmio_cors.yml file:
nelmio_cors:
defaults:
allow_credentials: true
allow_origin: ['*']
allow_methods: [ 'GET', 'OPTIONS', 'POST', 'PUT', 'PATCH', 'DELETE' ]
allow_headers: [ '*' ]
expose_headers: [ 'Authorization']
max_age: 0
hosts: []
origin_regex: true
forced_allow_origin_value: ~
paths:
'^/':
origin_regex: true
allow_origin: ['*']
allow_headers: [ '*' ]
allow_methods: [ 'POST', 'PUT', 'PATCH', 'GET', 'DELETE' ]
expose_headers: [ 'Link' ]
max_age: 3600
And added the below line in my .env:
###> nelmio/cors-bundle ###
CORS_ALLOW_ORIGIN=(.*)
###< nelmio/cors-bundle ###
And yet I get the same error and didn't manage to find an answer online.
Does anyone see what I've done wrong?
UPDATE
I've changed my nelmio_cors.yml config to the one above
And still got issues with cors but a different error message now:
Response {type: "cors", url: "https://localhost:8443/authentication_token", redirected: false, status: 404, ok: false, …}
It seems react don't manage to find the route. Any idea why ?
UPDATE 2
My nelmio_cors.yaml file now looks like that :
nelmio_cors:
paths:
'^/':
origin_regex: true
allow_origin: ['%env(CORS_ALLOW_ORIGIN)%']
allow_headers: ['*']
allow_methods: ['POST', 'PUT', 'PATCH', 'GET', 'DELETE']
max_age: 3600
.env contains:
CORS_ALLOW_ORIGIN=(.*)
But on the route call I receive the following error :
Access to fetch at 'https://localhost:8443/authentication_token' from origin 'http://localhost:3001' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'.
My response headers
access-control-allow-origin: http://localhost:3001
cache-control: no-cache, private
content-encoding: gzip
content-length: 451
content-type: application/json
date: Thu, 22 Oct 2020 08:12:11 GMT
server: openresty/1.17.8.2
status: 404
vary: Accept-Encoding
vary: Accept
x-debug-exception: Unable%20to%20find%20the%20controller%20for%20path%20%22%2Fauthentication_token%22.%20The%20route%20is%20wrongly%20configured.
x-debug-exception-file: %2Fsrv%2Fapi%2Fvendor%2Fsymfony%2Fhttp-kernel%2FHttpKernel.php:141
x-debug-token: 9b2891
x-debug-token-link: https://localhost:8443/_profiler/9b2891
x-powered-by: PHP/7.4.11
x-previous-debug-token: 486328
x-robots-tag: noindex
request header:
:authority: localhost:8443
:method: POST
:path: /authentication_token
:scheme: https
accept: application/json
accept-encoding: gzip, deflate, br
accept-language: fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7
content-length: 248
content-type: multipart/form-data; boundary=----WebKitFormBoundarywFASHmBarrNFyL7Y
cookie: pma_lang=fr; phpMyAdmin=a18f394d8e7daaefba20691da57c4b58; io=Jh7QElIlIXLDeAYaAAAA
origin: http://localhost:3001
referer: http://localhost:3001/
sec-fetch-dest: empty
sec-fetch-mode: cors
sec-fetch-site: cross-site
user-agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.99 Safari/537.36
I would suggest to have a different environmental variable value for local development and for your production or non-production environments.
nelmio_cors:
paths:
'^/':
origin_regex: true
allow_origin: ['%env(CORS_ALLOW_ORIGIN)%']
allow_headers: ['*']
allow_methods: ['POST', 'PUT', 'PATCH', 'GET', 'DELETE']
max_age: 3600
For local development you may have the following env.
CORS_ALLOW_ORIGIN=(.*)
For prod/non-prod you may want to list your web applications domains explicitly in order to be on a safe side.
CORS_ALLOW_ORIGIN=^https://(www\.)?(site.domain.com|site2.domain.com)$
For those who have the same issue, the problem came from the frontend
The data I recovered and place in body :
const response = await fetch(
'https://localhost:8443/authentication_token', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: data
})
were not well formated, and for some reason the backend sent back weird errors.
So I hardcoded them and this final result work :
const data = "{\"email\":\"test#test.com\",\"password\":\"test\"}";
const response = await fetch(
'https://localhost:8443/authentication_token', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: data
})
Related
I am quite new to k6 and load testing and I could not figure out why I am not able to push a token from one request to another, to test the login process in a Laravel-built web app. I hope somebody can help me out with this issue.
So my script looks like the following:
First request from where I want the token:
import { parseHTML } from 'k6/html';
import { sleep, group, check } from "k6";
import http from 'k6/http'
export const options = {}
export default function main() {
let response
group('page_1 - http://localhost:81/login', function () {
response = http.get('http://localhost:81/login', {
headers: {
host: 'localhost:81',
'user-agent':
'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:104.0) Gecko/20100101 Firefox/104.0',
accept:
'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
'accept-language': 'en-US,en;q=0.5',
'accept-encoding': 'gzip, deflate, br',
connection: 'keep-alive',
cookie:
'XSRF-TOKEN=eyJpdiI6InY5ckZiaGdFTkI4Q0YyRi8rdmtyNUE9PSIsInZhbHVlIjoiT0NjZXlWWVBubTE5Zjh6cXBmNmZFWTdZKzBjVXlEOGhheGR0aVUybURSSGRZbEFmQ0N2RW5BQ3pOYzBQUXgweXhUaGNpRDhrcTV5SHBJUkEvU0FYTmN3eCswYTFsVnhQdk8wL1dkeHMvOTNXRTU4dnk2WjJ0QWFCSWdyQzEwQkwiLCJtYWMiOiIyODI1YmFkMDI1MzlkOGY4ODEyMDg4YWU5M2I5MWE3NmI3Yjg2ODczYTBkMzhhNmZiZTU5ODNlZDBjOGViNWIzIn0%3D; dev_session=eyJpdiI6ImNGalhPQW9GTWlYLzdsaEg1Qk0zdnc9PSIsInZhbHVlIjoiVU5jQ21OZmkyUDVnUmd2WUxUc3Z5dWhRbzBJTm1HWFhmQ1RuNzdFaEpRb1IzdVlIa1VhUkNXYTBlc2IxMHRMajl6UTAzYmFVTHZheEdTV2RrYU84d3pmdEUxYUlkaVFFT3J5YUVWSE1wVklRektqemVmbjhmK3hLWHo2ZmlMYlgiLCJtYWMiOiI3MTQ2ODg0Yjk4YjhhNjg2Yzg1YjllZjdmMWMyNzVkY2ZmNGM1NjAzYWUyN2NlMmE0ZjAwOTAyNWMwNGI2YmM2In0%3D',
'upgrade-insecure-requests': '1',
'sec-fetch-dest': 'document',
'sec-fetch-mode': 'navigate',
'sec-fetch-site': 'none',
'sec-fetch-user': '?1',
'sec-gpc': '1',
},
})
// Query the HTML for an input field named "_token".
const elem = response.html().find('input[name=_token]');
// Get the value of the attribute "value" and save it to a variable
const token = Elem.attr('value');
// Now you can concatenate this extracted value in subsequent requests that require it.
// console.log() works when executing k6 scripts locally and is handy for debugging purposes
console.log('The value of the hidden field is: ' + token);
check(response, {
list_OK: (r) => r.status === 200,
});
})
Second request - I want to use the token from the previous request to log in:
group('page_2 - http://localhost:81/customlogin', function () {
const url = 'http://localhost:81/customlogin';
const payload = JSON.stringify({
_token: `${token}`,
email: 'user',
password: '1234',
});
const params = {
headers: {
'Content-Type': 'application/json',
host: 'localhost:81',
'user-agent':
'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:104.0) Gecko/20100101 Firefox/104.0',
accept:
'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
'accept-language': 'en-US,en;q=0.5',
'accept-encoding': 'gzip, deflate, br',
'content-type': 'application/x-www-form-urlencoded',
origin: 'http://localhost:81',
connection: 'keep-alive',
referer: 'http://localhost:81/login',
cookie:
'XSRF-TOKEN=eyJpdiI6ImlnZFZCUGF1b1FYUlJOdTJHNDd2Vnc9PSIsInZhbHVlIjoiTXhhdnZyQzlPamRFQ21rajdQVEZXcThzWittZndqU2d1L0hyN1BmRTA2a2RBbEpYZUhIUlRpWjh1RWJoQ1Y5dWJoTWVnaXEzZ1NVTjBndG1tenUyN2phY1lMdkIxSzBGek5aYndlSmRxaEhVTGY4WkNCcE1UY3N6YmowUnkrTkciLCJtYWMiOiJlNDIxNjhkYTc1NjYxNTVkNWZhOWViZDYwMGU1ODRkNmQ2ZGU0NjgyMjU5NjIxMzQ0MjYyYzRjMmJkYTVmNjUwIn0%3D; dev_session=eyJpdiI6IndxWXpobW9BUm1GSHNVZkorN0N0OGc9PSIsInZhbHVlIjoiSE82by9aRnBXQjFkNG5JMHFkVzUzc3kraUZOYUdIdjNlUGN6a3c2SjBSZy9TaVNxNmRsWnQzMTltMGt0MGQvWUoxQndyQXFvd2theWViNU94Z2FXaXlGTkc4ZVdERGY2KzRpUUZDZDIxNG85UFhhanRiajBCWElmcmthMWE0R3IiLCJtYWMiOiJjMDllMmRmNGJjNDRlMjM2MmZmZTViOWEwZmUzNWQ3MzNjZDI1NWQwYmU3MjE4OTZiMTRhN2U0NWNkMTcxMDAzIn0%3D',
'upgrade-insecure-requests': '1',
'sec-fetch-dest': 'document',
'sec-fetch-mode': 'navigate',
'sec-fetch-site': 'same-origin',
'sec-fetch-user': '?1',
'sec-gpc': '1',
},
};
response = http.post(url, payload, params);
console.log(response)
check(response, {
list_OK: (r) => r.status === 200,
});
})
After running the script I get an error message saying:
> ReferenceError: token is not defined
Thank you for your passionate help!
In this case you are defining a variable in the first call to group (const token ....` and then try to use it in the second call.
This has nothing to do with CSRF or k6, but with javascript ... and arguably scoping in most other languages.
But in order for both functions to see the same variable you will need to define it earlier - so for example next to your let response in the start of the default function.
Also remove const from the current definition as otherwise it won't work ;)
I know that this has been asked so many times, but none of the answers I've found seems to work. My app is React frontend and Flask backend via an api. I have just switched to axios from the usual await fetch and it keeps throwing CORS errors:
Access to XMLHttpRequest at 'http://127.0.0.1:5050/api/user/register' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
My code is thus:
const config = {
headers: {
"Access-Control-Allow-Origin": "*",
"Content-Type": "application/json" ,
},
}
const customFetch = axios.create({
baseURL: 'http://127.0.0.1:5050',
});
export const registerUser = createAsyncThunk(
'user/registerUser',
async (user, thunkAPI) => {
try {
const resp=await customFetch.post('/api/user/register', user, config);
return resp.data ;
}catch (error) {
return thunkAPI.rejectWithValue(error.response.data.msg);
}
}
);
My server has
CORS(app)
now also added:
#app.after_request
def add_security_headers(resp):
resp.headers['Access-Control-Allow-Origin']='*'
resp.headers['Access-Control-Allow-Methods']='GET, POST, PUT, OPTIONS'
resp.headers["Access-Control-Allow-Headers"]="Access-Control-Request-Headers,Access-Control-Allow-Methods,Access-Control-Allow-Headers,Access-Control-Allow-Origin, Origin, X-Requested-With, Content-Type, Accept"
return resp
and in any case it works ok for a standard:
await fetch(`${api_host}/api/user/register`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
data here ...
}),
});
its driving me mad, any clues? Thanks
UPDATE
Just in case there isn't enough info here are the request and response headers:
General
Request URL: http://127.0.0.1:5050/api/user/register
Request Method: POST
Status Code: 500
Referrer Policy: strict-origin-when-cross-origin
Request
POST /api/user/register HTTP/1.1
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-GB,en;q=0.9,en-US;q=0.8
Access-Control-Allow-Origin: *
Connection: keep-alive
Content-Length: 110
Content-Type: application/json
DNT: 1
Host: 127.0.0.1:5050
Origin: http://localhost:3000
Referer: http://localhost:3000/
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: cross-site
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36 Edg/105.0.1343.27
sec-ch-ua: "Microsoft Edge";v="105", " Not;A Brand";v="99", "Chromium";v="105"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Windows"
Response
HTTP/1.0 500 INTERNAL SERVER ERROR
Content-Type: text/html; charset=utf-8
X-XSS-Protection: 0
Connection: close
Server: Werkzeug/2.0.0 Python/3.8.10
Date: Fri, 09 Sep 2022 17:52:09 GMT
Once again, any suggestions gratefully received.
I added the following headers server-side, and it seems to have solved it.
I dont know why it stopped working when I switched axios. With standard asyc call it was fine.
resp.headers['Access-Control-Allow-Origin']='*'
resp.headers['Access-Control-Allow-Methods']='GET, POST, PUT, OPTIONS'
resp.headers["Access-Control-Allow-Headers"]="Access-Control-Request-Headers,Access-Control-Allow-Methods,Access-Control-Allow-Headers,Access-Control-Allow-Origin, Origin, X-Requested-With, Content-Type, Accept"
I am trying to pass a bearer token, to the fastify http server, in my headers.
I set the headers inside my request as:
...
const headers = {
Accept: 'application/json',
'Content-Type': 'application/json'
}
const token = localStorage.getItem('token')
if (token) {
headers['Authorization'] = `Bearer ${token}`
}
const newOptions = {
...options,
mode: 'no-cors',
headers
}
console.log('options:', newOptions)
return fetch(url, newOptions)
My console.log prints:
options: {
mode: "no-cors",
headers: {
Accept: "application/json",
Content-Type: "application/json",
Authorization: "Bearer NQ9xQLmYtq92aT8JHHRd7DGZJ..."
}
}
From the Chrome network tab, I look at the headers, and Authorization is just not present there. My route handler function is below:
async function user(server, options) {
server.route({
method: 'GET',
url: '/user/:email',
handler: async (req, res) => {
const username = req.params.email
console.log('user email:', username)
console.log('headers:', req.headers)
res.send({
type: 'promoter'
})
}
})
}
When I print headers on the server, it also does not have Authorization, showing:
headers: { host: 'localhost:5000',
connection: 'keep-alive',
pragma: 'no-cache',
'cache-control': 'no-cache',
accept: 'application/json',
'sec-fetch-dest': 'empty',
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.106 Safari/537.36',
'sec-fetch-site': 'same-site',
'sec-fetch-mode': 'no-cors',
referer: 'http://localhost:3000/admin',
'accept-encoding': 'gzip, deflate, br',
'accept-language': 'en-US,en;q=0.9,ru;q=0.8' }
What am I missing?
Another interesting issue is that when I run the request from Postman it shows 200 response code, and fastify prints 200 to the log. However, running from the saga/request with:
return fetch(url, newOptions)
.then(checkStatus)
.then(parseJSON)
I get response.status of 0 instead of 200 inside the request method, while the server log still shows "res":{"statusCode":200}.
I figured out what was the problem.
Apparently, my version of Chrome - Version 80.0.3987.106 (Official Build) (64-bit) and possibly other browsers and older versions of Chrome, as well, strip the authorization header, when it is used in conjunction with the no-cors mode. Enabling CORS and setting the appropriate headers solves the problem.
Try adding withCredentials: true and credentials: 'include' to your options:
options: {
mode: "no-cors",
withCredentials: true, // <-- ADD THIS
credentials: 'include', // <-- AND THIS
headers: {
Accept: "application/json",
Content-Type: "application/json",
Authorization: "Bearer NQ9xQLmYtq92aT8JHHRd7DGZJ..."
}
}
Reference: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials
I am trying to add Login with spring security JDBC authentication in spring boot and React. I added cors filter configuration to spring security config file to work with CORS. I can Login with when .csrf().disable() is disabled. but when I try to send same post request with with csrf token i am getting error "Request header field x-xsrf-token is not allowed by Access-Control-Allow-Headers in preflight response".
I tried solutions provided in other questios but it dosen't work for me.
response header
HTTP/1.1 500
Vary: Origin
Vary: Access-Control-Request-Method
Vary: Access-Control-Request-Headers
Access-Control-Allow-Origin: http://localhost:3000
Access-Control-Allow-Credentials: true
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Content-Type: application/json;charset=UTF-8
Content-Language: en-US
Transfer-Encoding: chunked
Date: Sun, 20 Jan 2019 06:23:40 GMT
Connection: close
request header
POST /login HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Content-Length: 81
Access-Control-Allow-Origin: http://localhost:3000
Accept: application/json, text/plain, */*
Origin: http://localhost:3000
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36
Content-Type: application/x-www-form-urlencoded
Referer: http://localhost:3000/login
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Cookie: JSESSIONID=5B64C3749B3DCBBB5072B827D59E8418
form data
username: vk%40gmail.com
password: admin
_csrf: 30955a56-abb5-443a-a029-d6b371f16e5a
I send csrf token to react app like this
CsrfToken token = (CsrfToken)request.getAttribute(CsrfToken.class.getName());
map.put("csrf", token.getToken());
this is Cors filter configuration
#Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("*"));
configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"));
configuration.setAllowCredentials(true);
configuration.setAllowedHeaders(Arrays.asList("authorization", "Cache-Control", "content-type", "xsrf-token"));
configuration.setExposedHeaders(Arrays.asList("xsrf-token"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
This axios POST request
export const addProjectTask = (username,password,csrf,history) => async dispatch => {
axios.post('http://localhost:8080/login',
Qs.stringify({
username: username,
password: password,
}), {
headers: {
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
"X-XSRF-TOKEN": csrf,
// Authorization: 'Bearer ' + csrf,
"Content-Type": "application/x-www-form-urlencoded"
},
credentials: 'include',
})
.then(function (response) {
console.log(response);
history.push("/");
})
.catch(function (error) {
console.log(error);
});
};
what am i doing wrong here?
first of all, I am very very new to react. I am trying to upload a file to my amazon S3 bucket using axios.
I get the signature url correctly but I don't know how to continue.. I tried this but it doesn't work.
The error I get is the following:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://xxx.s3.amazonaws.com/wolves.jpeg?AWSAccessKeyId=xxxxxxxxxx&Content-Type=image%2Fjpeg&Expires=1502773987&Signature=ZXQya8d3xZoikzX6dIbdL3Bvb8A%3D. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
import React, { Component } from 'react'
import Dropzone from 'react-dropzone'
import aws from 'aws-sdk'
import axios from 'axios'
export default class ImageAWS extends Component{
uploadFile(files){
console.log('uploadFile: ')
const file = files[0]
aws.config.update({
accessKeyId: 'xxxxxxxxx',
secretAccessKey: 'xxxxxxxx'
});
var s3 = new aws.S3();
var params = {
Bucket: 'xxx',
Key: file.name,
Expires: 60,
ContentType: file.type
};
s3.getSignedUrl('putObject', params, function(err, signedUrl) {
if (err) {
console.log(err);
return err;
} else {
console.log(signedUrl);
var instance = axios.create();
instance.put(signedUrl, file, {headers: {'Content-Type': file.type}})
.then(function (result) {
console.log(result);
})
.catch(function (err) {
console.log(err);
});
return signedUrl;
}
});
}
render () {
return (
<div>
Images Component
<Dropzone onDrop={this.uploadFile.bind(this)} />
</div>
)
}
}
OPTIONS https://xxbucket.s3.amazonaws.com/wolves.jpeg?
AWSAccessKeyId=xxxxxxxxxxxxxxxxxx&Content-Type=image%2Fjpeg&Expires=1502894764&Signature=FqAccUimhyrLgLBldVy%2Fkyx2Xmc%3D HTTP/1.1
Host: xxbucket.s3.amazonaws.com
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:54.0) Gecko/20100101
Firefox/54.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Access-Control-Request-Method: PUT
Access-Control-Request-Headers: access-control-allow-headers,access-control-allow-methods,access-control-allow-origin
Origin: http://localhost:8080
Connection: keep-alive
HTTP/1.1 403 Forbidden
x-amz-request-id: 4282B87BA935EF9A
x-amz-id-2: jWOwOQ/7BCzvw1xPmJroOzUBhbCmpfGx5HCPaPUvMoYTFMrlhoG5wN902B1brZ5cjYnKHMLWmpQ=
Content-Type: application/xml
Date: Wed, 16 Aug 2017 14:45:05 GMT
Server: AmazonS3
Content-Length: 514
<?xml version="1.0" encoding="UTF-8"?>
<Error><Code>AccessForbidden</Code><Message>CORSResponse: This CORS request is not allowed. This is usually because the evalution of Origin, request method / Access-Control-Request-Method or Access-Control-Request-Headers are not whitelisted by the resource's CORS spec.</Message><Method>PUT</Method><ResourceType>OBJECT</ResourceType><RequestId>4282B87BA935EF9A</RequestId><HostId>jWOwOQ/7BCzvw1xPmJroOzUBhbCmpfGx5HCPaPUvMoYTFMrlhoG5wN902B1brZ5cjYnKHMLWmpQ=</HostId></Error>
You'll need to add the required CORS headers to your dev server.
Read about CORS. Depending on your development server, search for the proper way to add response headers. Then, add the following headers to every response:
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS",
"Access-Control-Allow-Headers": "X-Requested-With, content-type, Authorization"
This will enable to request data from other websites on the web. Make sure you add them to the development version only(I assume you are learning, so that's OK). On production, you'll need to limit the "Access-Control-Allow-Origin": "*", to specific urls.
Further reading:
webpack dev server CORS issue
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
For those who are facing this issue while uploading files from front end,
Go to AWS S3 -> select your bucket -> permission tab -> scroll to last
Under section Cross-origin resource sharing (CORS), edit and drop your configuration
[
{
"AllowedHeaders": [
"Authorization",
"Content-Range",
"Accept",
"Content-Type",
"Origin",
"Range",
"Access-Control-Allow-Origin"
],
"AllowedMethods": [
"GET",
"PUT"
],
"AllowedOrigins": [
"*"
],
"ExposeHeaders": [
"Content-Range",
"Content-Length",
"ETag"
],
"MaxAgeSeconds": 3000
}
]
You can edit this as per your requirements.
Finally, Publish/Save it.
This will resolve your CORS issue.