Currently, I am utilizing Vue JS version 2.5 along with Axios:
"vue": "^2.5.17",
"vue-axios": "^2.1.4",
"axios": "^0.18.0",
The main issue I am facing involves making a POST call like so:
const data = querystring.stringify({
'email': email,
'password': password,
'crossDomain': true, // this is optional and added by me for testing purposes
});
var axiosConfig = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
// "Access-Control-Allow-Origin": "*",
'Accept': '*',
}
};
axios.post(url, data, axiosConfig)
.then((response) => {
console.log('response');
console.log(response);
})
.catch((error) => {
console.log('error');
console.log(error);
});
I have also attempted the call without the "axiosConfig" parameter. However, it consistently falls into the catch block with the message: Error: Network Error
In the Network tab of the browser, a 200 status code is displayed alongside a proper Response (featuring valid JSON). Although it appears to function correctly, Axios presents an error and no response.
A warning in the console reads:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://url/api/page. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
When attempting the same call through Postman, it performs successfully. The distinction lies in Axios sending the headers "Origin" and "Referrer" with my localhost:8080, which differs from the API URL being called.
Is there a way to execute this call from Axios without encountering this error? Thank you.
UPDATE
This operation functions as intended when using PHP:
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://myurl",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "------WebKitFormBoundaryTrZu0gW\r\nContent-Disposition: form-data; name=\"email\"\r\n\r\nemail\r\n------WebKitFormBoundaryTrZu0gW\r\nContent-Disposition: form-data; name=\"password\"\r\n\r\npassword\r\n------WebKitFormBoundaryTrZu0gW--",
CURLOPT_HTTPHEADER => array(
"Postman-Token: 62ad07e5",
"cache-control: no-cache",
"content-type: multipart/form-data; boundary=----WebKitFormBoundaryTrZu0gW",
"email: email",
"password: password"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
I merely copied the Postman-generated call and tested it on a different page, where it performed flawlessly. Hence, the issue pertains not to CORS but rather to my Javascript implementation.