I can't understand why Axios doesn't return set-cookies
Code:
axios({
url: 'https://*/bpms/engine/get_profile.php',
withCredentials: false, // true return same
auth: {
username: this.emailValue,
password: this.passwordValue
},
headers: {"Cache-Control": "max-age=0"}
})
.catch((error) => {
if (error) {
alert(error.response.data.error.description);
document.location.reload()
}
})
.then(response => {console.log(response.headers)})}
Browser network request:
Axios response.headers:
Related
Using SvelteKit 1.0.0-next.571
My application has a login route with:
+page.server.ts => redirects to / if locals.user is set
+page.svelte => show login page
signin/+server.ts => Login and get a jwt from graphql app running on the same machine.
+server.ts:
[..]
let gqlResponse = await response.json();
if ( gqlResponse.errors ) {
console.log("ERRORS FROM GRAPHQL MIDDLEWARE:", gqlResponse.errors);
return json( { error: gqlResponse.errors, isException: true } );
}
if (gqlResponse.data.login.user && !gqlResponse.data.login.error) {
opts.cookies.set('jwt', gqlResponse.data.login.token, {
path: '/',
maxAge: SESSION_MAX_AGE
});
opts.setHeaders( { 'Access-Control-Allow-Credentials': 'true' } )
opts.setHeaders({ 'Content-Type': 'application/json' })
}
return json( gqlResponse.data.login );
and the login handler in +page.svelte :
[..]
const fetchOptions = {
method: 'POST',
//mode: 'no-cors',
//redirect: 'follow' as RequestRedirect,
body: JSON.stringify(credentials),
credentials: 'include' as RequestCredentials
}
try {
const response = await fetch('/login/signin', fetchOptions);
const login = await response.json();
if (login.error) {
handleError(login);
return false;
}
} catch (e) {
return handleException(e);
}
goto('/', { replaceState: true, invalidateAll: true} );
This works fine in localhost, but connecting another device to the local network does not set any cookies making impossible to login:
Local: http://localhost:5173/
➜ Network: http://192.168.x.x:5173/
I also tried with different fetch options and cookie settings like:
opts.cookies.set('jwt', gqlResponse.data.login.token, {
path: '/',
httpOnly: true,
sameSite: 'strict',
// secure: true
maxAge: SESSION_MAX_AGE
});
but no luck, and now 'm stuck.
This is my JS code for the API
export const getUser = async (user) => {
//Working
const json = await fetch( "*****/username/getUser", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
user:user
}),
})
.then((res) => {
return res.json();
})
.catch((err) => {
console.log("Error in getUser: " + err);
});
return json;
};
Here is an attempt to make the request, which unfortunately return the authentication error.
fetchUser.request("kirolosM")
.then((result)=>{
console.log(result);
}).catch((err)=>{console.log("Error ",err);})
The error
{
"message": "Missing Authentication Token"
}
I have tested the API using postman and it is working as expexted.
Probably useful to compare the request sent from your json code to the one you're sending from postman. It looks like you need to include you auth token in your headers in your request.
Something like
export const getUser = async (user) => {
//Working
const json = await fetch( "*****/username/getUser", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authentication": `Bearer ${token}`
},
...
How can I prevent prettier from adding line breaks to the beginning of my .then() and .catch() statements
Expected
await Axios({
method: "GET",
url: test,
}).then((response) => {
...
}).catch((exception) => {
...
});
Actual
await Axios({
method: "GET",
url: test,
})
.then((response) => {
...
})
.catch((exception) => {
...
});
Returns a 404 error
Here is a request with react
const addItemToBasket = (item) => {
dispatch({type: ADD_ITEM_TO_BASKET, payload: item})
console.log(item.id, store.get('email'))
axios.defaults.xsrfCookieName = 'csrftoken'
axios.defaults.xsrfHeaderName = 'X-CSRFToken'
axios.post("http://localhost:8000/cart/add", {
uid: item.id, amount: 1, email: store.get('email')
})
.then((response) => {
console.log(response.data)
})
.catch((error) => {
console.log(error);
});
}
Here is the django function
I am facing an issue of receiving NULL response for the axios POST request I made. How do I correct this error?
I've tried to changing multipart/form-data into x-www-form-urlencoded and multipart/x-www-form-urlencoded
async submitUser() {
this.memberObj = {
id: this.memberObjLocal.id,
name: this.memberObjLocal.name,
password: this.memberObjLocal.password,
email: this.memberObjLocal.email,
password: this.memberObjLocal.password,
gender: this.memberObjLocal.gender,
experience: this.memberObjLocal.experience,
birth: this.memberObjLocal.birth,
phoneNum: this.memberObjLocal.phoneNum,
address: this.address,
introduce: this.introduce,
pic: this.pic
};
const config = {
headers: { "Content-Type": "multipart/form-data" }
};
var formData = new FormData();
for (let data in this.memberObj) {
console.log(data);
formData.append(data, this.memberObj[data]);
console.log(this.memberObj[data]);
}
for (var key of formData.entries()) {
console.log(key[0] + ", " + key[1]);
}
try {
let response = await this.$axios.$post("/users/", formData, config);
this.$router.push("/");
console.log(response) // null
} catch (e) {
console.log(e.response);
}
}
Please try to use like this
import axios from "axios";
//... your codes here
axios({
url: "/users/",
method: "post",
data: formData,
headers: config.headers
})
.then(response => {
this.$router.push("/");
console.log(response);
})
.catch(error => console.error(error));
//... and other codes here
and you can see more examples!