Why Axios is not providing response header when app is opening second time? - react-native

Here is my API request
const getData= async () => {
const cookie='workid_token=eyJra4rgrtF7SnlSETjIGrFYQy-P2SFmlE6A.Tw_rx0Ut_Kj9zLWRQ9X23w';
const qs = require('qs')
let body = qs.stringify({
gid: '1196'
})
await axios.post(
'https://www.google.com', body,
{
headers: {
'Cookie': cookie,
'Content-Type': 'application/x-www-form-urlencoded',
},
},
).then(response => {
console.log('data', response);
if (response.data.status === '1') {
const PHPSESSID = response.headers['set-cookie'];
var separatedvalue = PHPSESSID[0];
var sessid = separatedvalue.split('; path=/')[0];
}
}).catch(error => {
console.log(error);
});
};
I am implementing Axios API post request in my React Native application. When I run the application first time I am getting set-cookie value in response headers. If I kill the application and I open it second time I am not getting value in set-cookie. Also not receiving response from the API.
Note: I want to receive value from set-cookie all the times.

Related

Fetch Post of formData with images works in iOS but on android returns 400 BAD REQUEST

`I am using fetch on react native to send a post request with a form data object on the body.
This code works on iOS but on android it returns a 400 BAD REQUEST and I get ERROR [SyntaxError: JSON Parse error: Unexpected EOF].
const buildFormData = () => {
const data = new FormData();
for (let i = 0; i < photoForm.photosToUpload.length; i++) {
console.log(photoForm.photosToUpload[i].uri)
data.append('photosToUpload', {
uri: photoForm.photosToUpload[i].uri,
name: photoForm.photosToUpload[i].fileName,
type: 'image/jpeg'
});
data.append("userForm", JSON.stringify(userForm));
console.log(data)
return data;
}
This is how I am building my form data.
export const createUser = (formData) => async (dispatch) => {
try {
const headers = {
'Content-Type': 'multipart/form-data'
};
const response = await fetch('https://c66d-2a02-a03f-a5a1-e400-1573-78c6-e019-e601.eu.ngrok.io' + '/create_user', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data',
},
body: formData,
})
.then(response => response.json())
.then(responseJson => {
console.log(responseJson);
})
.catch(error => {
console.error(error);
});
Handle successful response
catch (error) {
Handle error
}
This is how I am sending the form data to my django server. I know the problem is in the form data because if I dont send files the request goes through.
I have read almost every github issue on this matter, switched to axios, tried multiple solutions and no luck. Does anyone know what the problem can be?
I tried to make a post request using fetch and it works on iOS but not on android.
I was expecting to work on both OS.`

Axios : authorization header not set on specific request on some iOS devices

I have a vuejs app using axios for http requests.
The authorization header is set via a request interceptor like so :
const api = axios.create({
baseURL: process.env.API_URL,
crossdomain: true,
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
});
api.interceptors.request.use(
function (config) {
if (config.url !== "/register") {
const accessToken = localStorage.getItem('token');
if (accessToken) {
config.headers.Authorization = "Bearer " + accessToken;
}
}
return config;
},
function (error) {
// Do something with request error
return Promise.reject(error);
}
);
All the requests made in the app go through this interceptor. But there is a request for which the authorization header is not set for some ios devices (it works fine on web/android devices and some ios devices). Here is the request :
export function getSessions(context, payload) {
return new Promise((resolve, reject) => {
api.get("/sessions/" + payload.sportId + "/?begin=" + payload.period.from + "&end=" + payload.period.to)
.then(({ data }) => {
resolve(data);
})
.catch((error) => {
reject(error);
});
});
}
I don't understand what could be going wrong. All other requests work fine one the devices for which this one doesn't.
I found the reason of the bug : there was a / before the query (/?begin=). The problem occurred on iOS 14.5, 14.7 and maybe other versions but on any other device there was no error, sometimes a 301 http code was answered but that's it.

Trying to set a cookie established on a web session as a header back to API

I am trying to login via the webfront end and trying to intercept a cookie and then using that in the subsequent API request. I am having trouble getting the cookie back into the GET request. Code posted below.
import https from 'https';
import { bitbucketUser } from "../userRole.js"
import { ClientFunction } from 'testcafe';
fixture `Request/Response API`
// .page `https://myurl.company.com/login`
.beforeEach(async t => {
await t.useRole(bitbucketUser)
});
test('test', async t => {
const getCookie = ClientFunction(() => {
return document.cookie;
});
var mycookie = await getCookie()
const setCookie = ClientFunction(mycookie => {
document.cookie = mycookie;
});
var validatecookie = await getCookie()
console.log(validatecookie)
const executeRequest = () => {
return new Promise(resolve => {
const options = {
hostname: 'myurl.company.com',
path: '/v1/api/policy',
method: 'GET',
headers: {
'accept': 'application/json;charset=UTF-8',
'content-type': 'application/json'
}
};
const req = https.request(options, res => {
console.log('statusCode:', res.statusCode);
console.log('headers:', res.headers);
let body = "";
res.on("data", data => {
body += data;
});
res.on("end", () => {
body = JSON.parse(body);
console.log(body);
});
resolve();
});
req.on('error', e => {
console.error(e);
});
req.end();
});
};
await setCookie(mycookie)
await executeRequest();
});
I have tried several examples but am quite not able to figure what is it that I am missing.
When you call the setCookie method, you modify cookies in your browser using the ClientFunction.
However, when you call your executeRequest method, you run it on the server side using the nodejs library. When you set cookies on the client, this will not affect your request sent from the server side. You need to add cookie information directly to your options object as described in the following thread: How do I create a HTTP Client Request with a cookie?.
In TestCafe v1.20.0 and later, you can send HTTP requests in your tests using the t.request method. You can also use the withCredentials option to attach all cookies to a request.
Please also note that TestCafe also offers a cookie management API to set/get/delete cookies including HTTPOnly.

Network Error when sending file in react native with axios

I am trying to send a file to a nodejs server from react native using axios, this is my code:
const createFormData = (file) => {
const data = new FormData();
data.append('message', text);
data.append('receiver',doctorid);
if(file !== ''){
data.append('file', {
type: file.type,
uri: file.uri,
name: file.name.replace(/\s/g,'')
})
}
return data;
}
const onSend = async() => {
const newMessages = [...messages]
newMessages.push({"sender": currentuserID, "id": 339, "message": 'sending...', "attachment": '', "receiver": doctorid, "type": 0},)
setMessages(newMessages)
const token = await AsyncStorage.getItem('token');
const data = createFormData(singleFile)
await appApi.post('/chats', data, {
headers: { 'Authorization': 'Bearer ' + token }
}).then(()=>{
socket.emit('sendmessage', text, (err) => {
messageInit()
});
})
.catch(err => console.log(err.message))
}
This code works perfectly if there's no image attached, but ones there's an image attached, I get the network error message immediately.
For a little bit of troubleshooting, I tried sending request to my local machine, using ngrok. From ngrok, I realized the request wasn't sent at all to the url. So it just fails immediately, without the request been made to the url.
Anyone with solution to this.
I'm testing on an android emulator
send using formdata
try this
let formData = new FormData();
let imagefile = document.querySelector('#file');
formData.append("image", imagefile.files[0]);
axios.post('upload_file', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})

React native set cookie on fetch/axios

I am trying to set the cookie on fetch or axios, I already checked the solutions posted on github or stackoverflow, but none of them are working now.
I'm using Saml for authentication on my RN project.
So Here are stories:
on the first login, if the user clicks the start button, it calls the api of get profile info, if there is no cookie on header, it returns redirect url and also cookie(it's unauth cookie), and go to the url on the webview, after the user logins on the webview, then the original url(get profile api) is called on webview, after that, I'd grab the auth cookie using react-native-cookies library, and then set it on the header of fetch/axios. but it doesn't work.
export async function getMyProfile() {
const cookies = await LocalStorage.getAuthCookies();
await CookieManager.clearAll(true)
const url = `${Config.API_URL}/profiles/authme`;
let options = {
method: 'GET',
url: url,
headers: {
'Content-Type': 'application/json',
},
withCredentials: true
};
if (cookies) options.headers.Cookie = cookies.join(';')
return axios(options)
.then(res => {
console.info('res', res);
return res;
}).catch(async (err) => {
if (err.response) {
if (err.response.status === 401) {
const location = _.get(err, 'response.headers.location', null);
const cookie = _.get(err, 'response.headers.set-cookie[0]', null);
await LocalStorage.saveUnAuthCookie(cookie);
return { location, cookie, isRedirect: true };
}
}
});
}
You could use Axios interceptor.
let cookie = null;
const axiosObj = axios.create({
baseURL: '',
headers: {
'Content-Type': 'application/json',
},
responseType: 'json',
withCredentials: true, // enable use of cookies outside web browser
});
// this will check if cookies are there for every request and send request
axiosObj.interceptors.request.use(async config => {
cookie = await AsyncStorage.getItem('cookie');
if (cookie) {
config.headers.Cookie = cookie;
}
return config;
});