I have tried everything and can't get Axios to work with SAP Odata Post services. The problem is CSRF token validation failing but its working fine in Postman.
My request looks like this:
const postNewTasks = async (body, headers) => (await axios.get(getHeadersandCFRSURL, {
headers: { 'authorization': auth, 'x-csrf-token': 'fetch' },
withCredentials: true
}).then((response) => {
axios({
method: 'POST',
url: postBatchOperationsURL,
headers: {
"Authorization": auth,
"Content-Type": "multipart/mixed; boundary=batch_1",
"X-CSRF-Token": response.headers["x-csrf-token"], // set CSRF Token for post or update
},
withCredentials: true,
body: body
}).then(function (response) {
console.log(response)
return response
}).catch(function (err) {
console.log(err)
return err
})
})
)
Anybody has idea why the CSRF token validation fails with this axios request?
I had this issue recently and a solution that worked for me was to add a Cookie
header with the cookies from the initial response set-cookie
headers.
Postman does this automatically, but axios doesn't it would seem. My code from that part after "x-csrf-token":"fetch"
:
var xcsrftoken = response.headers["x-csrf-token"];
var cookies = '"';
for (var i = 0; i < response.headers["set-cookie"].length; i++) {
cookies += response.headers["set-cookie"][i] + ";";
}
cookies += '"';
axiosClient.defaults.headers.common[this.xcsrftokenName] = xcsrftoken;
axiosClient.defaults.headers.common["Cookie"] = cookies;
axiosClient
is the object made from axios.create
. I've set those headers as default so that I don't need to include them later in the requests. There were multiple set-cookie
headers as well and it was necessary to combine them into one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With