React native fetch/XMLHttpRequest post request with multiple set-cookie - react-native

I want to receive multiple Set-Cookie values from a web server.
Currently i'm only receiving the last Set-Cookie in my header.
XMLHttpRequest:
var formData = new FormData();
formData.append('userId', state.userId);
formData.append('password', state.password);
var http = new XMLHttpRequest();
var url = "http://myurl";
http.open("POST", url);
http.setRequestHeader("Content-type", "multipart/form-data");
http.withCredentials = true;
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
console.log(http.responseText);
console.log(http.getAllResponseHeaders());
}
}
http.send(formData);
Fetch:
fetch('http://myurl', {
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data',
},
credentials: 'same-origin',
body: formData
})
.then((response) => {
console.log(response);
console.log(response.headers.getAll('set-cookie'));
return response.json()
})
.then((responseJson) => {
console.log('responseJson', responseJson);
console.log('formData', formData);
setLoginBool(responseJson.success);
})
.catch((error) => {
console.error(error);
});
I have added the result of a postman request and the log of the fetch result.
It seems only the last Set-Cookie value is being received.
postman result
fetch log result

Related

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

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.

how make put axios request with formData?

i tried to send data with text and file. i created formData to send it:
updateProduct(item){
let product = new FormData();
product.append('thumb', item.thumb)
product.append('weight', item.weight)
this.$store.dispatch('UPDATE_PRODUCT', product)
},
action in store:
UPDATE_PRODUCT({commit}, item){
const token = localStorage.getItem('token');
const config = {
headers: { Authorization: `Bearer ${token}`}
};
// console.log(token)
return axios.post(`${url}`, item, config)
.then((resp) => {
commit('UPDATE_PRODUCT_IN_STATE', resp)
return resp;
})
.catch((error) => {
console.log(error);
});
},
So i have 422 error. Why?

redirecting get request to post request? using express

Is that possible to redirect from Get request to POST request using Express JS? I'm just redirecting from API merchant a get request and need to throw a data back that's why i need to use POST request to send it back.
router.get('/webhooks/success',(req, res) => {
res.redirect(307, '/webhooks/success')
})
router.post('/webhooks/success', async function(req, res){
try{
var request = require('request');
var buffer = Buffer.from('pk-7xvHjw43SOGNLpot677GfxoLasdasdaa44TOJkREVMo')
var base = buffer.toString('base64');
let auth = 'Basic ' + base
var options = {
'method': 'POST',
'url': 'url',
'headers': {
'Content-Type': 'application/json',
'Authorization': JSON.stringify(auth)
},
body: JSON.stringify({
......
})
};
// req.setHeader(options)
request(options, async function (error, response) {
if (response === null || response === undefined || error) throw createError(403, error)
console.log('RESPONSEE', response)
if (response.statusCode === 200) return res.redirect('/success');
throw createError(500, error)
});
}catch(e){
error_logs(e, req)
req.flash('error', e.message)
res.redirect('back')
}
});
I Just ended up by using another api post request
router.get('/webhooks/success',async (req, res) => {
try{
var request = require('request');
var options = {
'method': 'POST',
'url': 'url',
'headers': {
'Content-Type': 'application/json',
}
}
request(options, async function (error, response) {
if (response === null || response === undefined || error) throw createError(403, error)
if (response.statusCode === 200) return res.redirect('/success');
res.redirect('/buy_ticket')
});
}catch(e){
error_logs(e, req)
req.flash('error', e.message)
res.redirect('/buy_ticket')
}
})

Reading post data from react-native

I have this fetch() method that is sending data from my react-native app to a laravel method
async handleSubmit(){
var me = this.state.message;
console.log('this connected',me);
try {
let response = await fetch('http://no-tld.example/androidLogin', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: 'chesterfield#gmail.com',
password: '123456',
})
});
//let res = await response.text();
if (response.status >= 200 && response.status < 300) {
console.log(response);
} else {
//Handle error
// let error = res;
// throw error;
}
} catch(error) {
//console.log(res);
}
}
I can receive the data using this method
public function androidLogin(){
$rawData = file_get_contents("php://input");
$postedValue = json_decode($rawData);
//parse_str($postedValue, $output);
return response()->json([
'name' => $postedValue,
'route' => $postedValue
]);
}
and attempting to return the just posted data. The posted data looks like this
12:35:07 PM:
{"type":"default","status":200,"ok":true,"headers":{"map":{"connection":["Keep-Alive"],"content-length":["54"],"content-type":["application/json"],"set-cookie":["XSRF-TOKEN=eyJpdiI6IlF1NWlLOE9rVCtlUXNpYzBFSTV0c0E9PSIsInZhbHVlIjoiNWtGenprRmJOYTVsc2dQRjNrcmpxZXhWeFZRd1NZSzdiOWFKUUZTZmJJaEN6U0RnbW9uOVZ4bGUrV2ZMYUlIb0NQNHFrT1pCWXB0dnlwTjhPWm56ZWc9PSIsIm1hYyI6IjU3NDJkNWE5M2U4YmIwNTUwNzhkZTM4ZTRlNDc5OTZhNjczYWEyODU0OGNmN2ViNDdkYTM4YjdjY2U1ZWE1ZmYifQ%3D%3D;
expires=Fri, 09-Jun-2017 11:35:07 GMT; Max-Age=7200; path=/,
laravel_session=zqcMrXeuwwGpEsR8Jh2WakDg0cdqLod4QsfMnfcd; expires=Fri,
09-Jun-2017 11:35:07 GMT; Max-Age=7200; path=/;
HttpOnly"],"access-control-allow-methods":["GET, POST, PUT, DELETE,
OPTIONS"],"access-control-allow-origin":["*"],"cache-control":["no-cache,
private"],"server":["Apache/2.4.18
(Ubuntu)"],"keep-alive":["timeout=5, max=100"],"date":["Fri, 09 Jun
2017 09:35:07
GMT"]}},"url":"http://no-tld/androidLogin","_bodyInit":"{\"email\":\"chesterfield#gmail.com\",\"password\":\"123456\"}","_bodyText":"{\"email\":\"chesterfield#gmail.com\",\"password\":\"123456\"}"}
I now want to access the returned email from my native-react app.
console.log(response.email); returns null. How can i access the returned email value in react native?
Try below fetch call,
React-native log-android //Android
or react-native log-ios // IOS
use to see response data or error details
fetch('http://no-tld.example/androidLogin', {
method: 'POST',
headers: { 'Accept': 'application/json','Content-Type': 'application/json',},
body: JSON.stringify({ email: 'chesterfield#gmail.com', password: '123456'})
}).then((response) => response.json())
.then((responseData) => {
console.log("responseData : " +responseData); // fetch response data
}).catch((error) => {
console.log("error : " +error); // error
});
I fixed it this way
async handleSubmit(){
var me = this.state.message;
console.log('this connected',me);
try {
let response = await fetch('http://198.74.51.225/androidLogin', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: 'chesterfield#gmail.com',
password: '123456',
})
});
let res = await response.text();
if (response.status >= 200 && response.status < 300) {
let userData = JSON.parse(res);
console.log(userData.email);
} else {
//Handle error
// let error = res;
// throw error;
}
} catch(error) {
//console.log(res);
}
}
Just to be sure of the post data returned, you can modify the posted data in the server side and return it using this function
//Android Login
public function androidLogin(){
$rawData = file_get_contents("php://input");
$postedValue = json_decode($rawData,true);
$token = rand(400,7833);
return response()->json([
'email' => $token."_".$postedValue['email'],
'password' => $postedValue['password']
]);
}
For this to work, i had to also allow cors using this middleware
<?php
namespace App\Http\Middleware;
use Closure;
class Cors {
public function handle($request, Closure $next)
{
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
}
}
and i used it in my route like this
//Android
Route::group(['middleware' => ['cors']], function() {
Route::post('androidLogin', 'Auth\LoginController#androidLogin');
});
Hope that helps someone trying to post or get from a react-native app.

How to obtain access token from Yelp Fusion API using NodeJS

I am trying to obtain the access token for Yelp's API.
Yelp's API documentation:
https://www.yelp.com/developers/documentation/v3/get_started
I keep running into the error below on my terminal:
problem with request: getaddrinfo ENOTFOUND api.yelp.com/oauth2/token api.yelp.com/oauth2/token:80
Here's my NodeJS code (I took a lot of it from the Node Documentation site):
var http = require("http");
var postData = JSON.stringify({
"grant_type": "client_credentials",
"client_id": "<<client id>>",
"client_secret": "<<client secret no.>>"
});
var options = {
hostname: 'api.yelp.com/oauth2/token',
port: 80,
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(postData)
}
};
var req = http.request(options, (res) => {
console.log(`STATUS: ${res.statusCode}`);
console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
res.setEncoding('utf8');
res.on('data', (chunk) => {
console.log(`BODY: ${chunk}`);
});
res.on('end', () => {
console.log('No more data in response.');
});
});
req.on('error', (e) => {
console.log(`problem with request: ${e.message}`);
});
// write data to request body
req.write(postData);
req.end();
Two items that caught my eye:
Separate the hostname and the path in your options variable.
The YELP Fusion API is HTTPS, not HTTP. Using HTTP may result in a 302 response (URL Redirection).
var https = require('https');
getYelpAccessCode(function(response) {
var responseData = JSON.parse(response);
if (responseData != null) {
var accessCode = responseData.token_type + " " + responseData.access_token;
}
});
function getYelpAccessCode(callback) {
const postData = querystring.stringify({
'client_id': YELP_CLIENT_ID,
'client_secret': YELP_CLIENT_SECRET
});
const options = {
hostname: 'api.yelp.com',
path: '/oauth2/token',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(postData)
}
};
const req = https.request(options, (res) => {
console.log(`STATUS: ${res.statusCode}`);
console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
var body = '';
res.setEncoding('utf8');
res.on('data', (chunk) => {
body += chunk;
console.log(`BODY: ${chunk}`);
});
res.on('end', () => {
console.log('No more data in response.');
callback(body);
});
});
req.on('error', (e) => {
console.error(`problem with request: ${e.message}`);
});
// write data to request body
req.write(postData);
req.end();
}