React, Axios issue: Response for preflight does not have HTTP ok status ( 404 not found ) - authentication

I've been trying using axios with basic auth but it always returns not found.
Here is my code
const ROOT_URL='http://localhost/b2b_ecom/b2b-api/index.php/api/';
export function login () {
return function(dispatch)
{
const api = axios.create({
mode: 'no-cors',
credentials:'include',
redirect: 'follow',
auth: {
username: 'mouad#b2b.dz',
password: '123456'
},
headers: {
'Content-Type': 'application/json',
}
});
api.post(`${ROOT_URL}site/login `).then(function(response)
{
dispatch({LOGIN,payload:response.data});
return true;
}).catch(function(error)
{
return error;
});
} ;
}
And here it is the error I got:
OPTIONS http://localhost/b2b_ecom/b2b-api/index.php/api/site/login 404 (Not Found)
Failed to load http://localhost/b2b_ecom/b2b-api/index.php/api/site/login: Response for preflight does not have HTTP ok status.
Screenshot

I think browser is adding access control header to request.
Check the following things
1) When you hit from postman or other such api clients this api should be working properly. (even curl is fine)
2) Try adding Access-Control-Allow-Origin as * for this request on server and see if it works.

Related

No Set-Cookie header on Axios

I am using a Symfony API backend and want to authenticate by REST call via Axios inside a Vue App.
The authentication works fine when using POSTMAN. It stores a session cookie and resends it on subsequent requests.
However, when I use Axios it won't give me the Set-Cookie header.
What I tried so far:
Adjusted CORS settings on Symfony backend (no CORS errors - all routes working)
Set { withCredentials: true } as config parameter on Axios post request.
Symfony EventSubsriber for injecting CORS headers:
public function onKernelResponse(ResponseEvent $event)
{
$response = $event->getResponse();
$response->headers->set('Access-Control-Allow-Methods', '*');
$response->headers->set('Access-Control-Allow-Headers', [ 'Content-Type', 'Set-Cookie' ]);
$response->headers->set('Access-Control-Allow-Origin', 'http://localhost:3000');
$response->headers->set('Access-Control-Allow-Credentials', 'true');
$response->setStatusCode(200);
}
Note that this is for local testing only.
Axios Request:
login(user, pw) {
return axios.post(cfg.apiUrl + '/api/login', {
username: user,
password: pw
},
{ withCredentials: true }
);
}
Follow up request:
test() {
return axios.get(cfg.apiUrl + '/api/test');
}
Could someone point out what I am still missing? Why do I get the header on POSTMAN, but not on Axios?
The solution is to also add the { withCredentials: true } in further requests. As it seems, it is not possible to read the Set-Cookie header via Axios, as #jub0bs pointed out.
The correct code for a follow-up request looks like:
test() {
return axios.get(cfg.apiUrl + '/api/test', { withCredentials: true });
}

How to set cookie header in post request

Here is my code:
axios
.post(
'https://app.adhg.ashdg/m/api/business/get-business',
{
'gid': getgid,
},
{
headers: {
'Cookie': cookie,
'Content-Type': 'application/x-www-form-urlencoded',
},
},
)
.then(function (response) {
// handle success
alert(JSON.stringify(response.data));
})
.catch(function (error) {
// handle error
alert(error.message);
});
I am implementing Axios post request in my React Native application. I want to send formurlencoded parameters along with the header called cookie.
In cookie I am storing AWS token value to send. But I am not getting the response, it says cookie is not sent. The same URL with params working perfectly in Postman. How can I pass cookie in the header?
Try something like this Cookie: name=value.
Mozilla Web Docs

Response to preflight request doesn't pass access control No 'Access-Control-Allow-Origin'

I have a Vue.js application that uses axios to send request to ApiGee Server.
This is the code i use to send request to APIgee.
const headers = {
'X-API-Key': 'randomKey123123'
}
return axios({
method: 'get',
url: url,
headers: headers
}).then(response => {
console.log(response)
})
from the ApiGee, I can see OPTIONS request being received first since I done the request from the client side browser.
I can also see the X-API-Key header key but the value is missing.
The error I'm getting from the browser console is
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource
Below code helped me you can try this format:
created() {
// POST request using axios with set headers
const article = { title: "Vue POST Request Example" };
const headers = {
'X-API-Key': 'randomKey123123'
};
axios.post(url, article, { headers })
.then(response => console.log(response.data)
);
}

GET request works in postman but fails with Axios

I'm sending GET request to the same endpoint with the same headers, including the Bearer, but while i get 200 and the correct JSON as a result when calling from Postman, when i send the request using Axios in my (Vue) project i get 302.
the call from the local project , running on localhost:8080 (in case its useful) is as follows:
const { authToken, userID } = store.getters.authUser
const config = {
method: 'get',
url: '/' + userID,
headers: {
Authorization: `Bearer ${authToken}`,
'Content-Type': 'application/json'
}
}
axios(config)
.then(res => {
console.log(res)
return res
})
.catch(e => {
console.log(e)
})
while in postman all i do is create a GET request with the same url and all i add in the headers is the 'Bearer ...'
the error i get from axios is :
Error: Network Error
at createError (createError.js?2d83:16)
at XMLHttpRequest.handleError (xhr.js?b50d:87)
and response status is 302 , any idea whats going on here??
both values of userID and the authToken exists and are equal to the same values i used with postman, same goes for the url

How to handler server redirect from axios

I have a vue web app that uses axios to communicate with an API. The authentication is handled by the server, and not by my app. That is, the server ensures that the user cannot see the app before they have authenticated.
Of course, after some time the user's authentication token expires and my app only notices this when it fires off a get/post request to the API. When this happens the axios request returns a redirect to a login page that, when printed to the console, looks something like this:
config: Object { url: "https://...url for my request...",
method: "get", baseURL: "...base url for api", … }
data: "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" \"http://www.w3.org/TR/REC-html40/loose.dtd\">\n<HTML>\n<HEAD>\n<TITLE>Need Authentication</TITLE>\n<link rel=\"stylesheet\" href=\"/Steely.css\" type=\"text/css\">\n</HEAD>\n<BODY>....</BODY>\n</HTML>\n"
headers: Object {
connection: "Keep-Alive",
"content-encoding": "gzip", "content-length": "1686", …
}
request: XMLHttpRequest {
readyState: 4, timeout: 0, withCredentials: false, …
}
status: 200
statusText: "OK"
<prototype>: Object { … }
app~d0ae3f07.235327a9.js:1:97292
What is the best way to redirect the user to this login page and then resume my original request? At the moment I am not even succeeding in recognising this. My axios code tries, and fails, to recognise when this happens and then redirect to user a vue component that has a login page. The relevant part of code looks like this:
export default new class MyAPI {
constructor() {
this.axios = axios.create({
headers: {
'Accept': 'application/json',
'Cache-Control': 'no-cache',
'Content-Type': 'application/json',
},
baseURL: `https://.../api`,
});
}
// send a get request to the API
GET(command) {
return new Promise((resolve, reject) => {
this.axios.get(command)
.then((response) => {
if (response && response.status === 200) {
if ( response.data && typeof response.data == 'string' && response.data.includes('Require authentication') ) {
store.dispatch('authenticate', this.baseURL+'/'+command).then( (resp) => resolve(resp.data) )
} else {
resolve(response.data);
}
} else {
reject(response.data);
}
})
.catch((err) => { reject('Internal error'+err); });
});
}
}
This results in the dreaded
Internal errorTypeError: e(...) is undefined
error, although this error is almost certainly triggered further down the code since I not recognising the login authentication request.
Is anyone able to recommend how best to recognise and process the login request?