Yeah another problem with CORS and ajax request :)
I went a lot through the web but still I am stuck with a preflight request which get a 401 Unauthorized response. It has to be with the custom header added (x-access-token) since queries not using it are working. Any help would be greatly appreciated.
Context
A SPA (react/webpack) hosted at 127.0.0.1:3000, a mock web service (php/wamp) hosted at 127.0.0.1
The preflight request headers
OPTIONS /mock/getVisitList HTTP/1.1
Host: 127.0.0.1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:82.0) Gecko/20100101 Firefox/82.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Access-Control-Request-Method: GET
Access-Control-Request-Headers: x-access-token
Referer: http://127.0.0.1:3000/visitList
Origin: http://127.0.0.1:3000
DNT: 1
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
The response headers
HTTP/1.1 401 Unauthorized
Date: Fri, 30 Oct 2020 19:02:18 GMT
Server: Apache/2.4.41 (Win64) PHP/7.3.12
X-Powered-By: PHP/7.3.12
Access-Control-Max-Age: 1000
Access-Control-Allow-Origin: http://127.0.0.1:3000
Access-Control-Allow-Methods: POST, GET, PUT
Access-Control-Allow-Headers: x-access-token, content-type
Content-Length: 0
Keep-Alive: timeout=5, max=98
Connection: Keep-Alive
Content-Type: text/html; charset=UTF-8
The .htaccess
Header set Access-Control-Max-Age "1000"
Header add Access-Control-Allow-Origin "http://127.0.0.1:3000"
Header set Access-Control-Allow-Methods "POST, GET, PUT"
Header set Access-Control-Allow-Headers "x-access-token, content-type"
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule . index.php [L]
The JS method
const getVisits = async(token) => {
try {
const fetchResponse = await fetch(
`${baseUrl}getVisitList`,
{
method: 'GET',
headers: {
'x-access-token': token
}
}
)
switch(fetchResponse.status) {
case 200:
const data = await fetchResponse.json()
return data
case 401:
console.log('Unauthorized')
return null;
default:
console.log('Unhandled status at getVisits', fetchResponse.status)
return []
}
} catch(error) {
console.log('getVisits on error', error)
return []
}
}