When i send a normal get request to my deployed nodejs webserver it tell me there is no cookies sent in the header while i ve already write it in the headers of my api service
my service
constructor(private http: HttpClient, private global: Global) { }
verifAuth() {
return new Promise((resolve, reject) => {
this.http.get(`${this.global.url}verif`, this.global.header)
.toPromise()
.then(res => { resolve(res); })
.catch(err => { reject(err); console.log('err', err) });
});
my declared default header
#Injectable({
providedIn: 'root'
})
export class Global {
url: String; header;
constructor() {
this.url = "https://fmm.etudiant.xyz/";
this.header = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'cookies': `xt=${appSetting.getString('xt')}`,
}),
withCredentials: true
};
}
}
and when i debug the request i found this
request header
i expect that the token must be parsed and get the result of user but the backend server tell that there is no cookies while it work fine with an other website
Sending Cookie in Http request is not yet supported, there is a open feature request at Github.
Related
I make several requests from a React Native app to an API. Every request works fine both on iOS and Android except the DELETE method that does not work on Android. The call is correctly made, it goes through the API and the objects are deleted. But instead of getting the response, the call falls under the catch statement with [TypeError: Network request failed]. This does not happen in iOS.
Some people with the same problem were missing 'Content-Type': 'application/json' on the request headers which is not my case.
This is happening both locally, in testing and production stages (using an ip instead of localhost will do nothing).
The request is also successfully performed in Postman.
What can it be?
React Native 0.63.5
export const deleteApi = async (api: string, body?: any) => {
const userResponse = await getUserCredentials();
const authState = await getAuthState();
let response = await fetch(api, {
method: 'DELETE',
headers: await getHeaders(userResponse, authState),
body: JSON.stringify(body)
});
if (response.status === UNAUTHENTICATED_CODE)
response = await interceptor(response, userResponse, {
api: api,
method: 'DELETE',
body: body
});
return response;
};
leaveClass = async (
uuid: string,
onSuccess: () => void,
onFailure: (error: string) => void,
) => {
this.setLoading(true);
try {
const api = LEAVE_CLASS_API_PREFIX + uuid + LEAVE_CLASS_API_SUFFIX;
const response = await deleteApi(api);
if (response.status === SUCCESS_STATUS_CODE) {
onSuccess();
}
else {
const jsonResponse = await response.json();
if (jsonResponse.detail) onFailure(jsonResponse.detail);
else onFailure(translations.SOMETHING_WENT_WRONG);
}
} catch (error) {
console.log('leaveClass error: ', error);
}
this.setLoading(false);
};
You can use a network plugin for Flipper (https://fbflipper.com/docs/setup/plugins/network/), copy your request from it as a curl, and try to perform it from your terminal or postman. If it has the same error, the problem is not in React Native.
I created a simple app with react-native, using expo & Axios (for server requests)
Before build, while developing, all https requests worked fine.
After build, when running the apk on a physical device, https is not working at all.
The error I get with Logcat is "Network Error".
Other Internet connections (after build) in the app do work, like webview opening a web page or Firebase connections also.
analyzerApi.post('/analyze', urls) .then((res) => {
dispatch({type: 'get_result', payload: res.data.analysis})}).catch(err => console.log("Error in getting analyze.. " ,err.name, err.message))
(analyzerApi is an axios instance with baseUrl directed to my server)
This call will work for both HTTP and HTTPS Try this example for POST CALL
fetch('http://mywebsite.com/endpoint/', {
method: "POST",
headers: {
// Authorization: "Bearer " + Token,
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
// sending data userID username, password, etc
}),
})
.then((response) => response.json())
.then((responseJson) => {
// Response will here
})
.catch((error) => {
alert(error);
});
Try this example for GET CALL
fetch('http://mywebsite.com/endpoint/', {
method: "GET",
headers: {
// Authorization: "Bearer " + Token,
// OR USER name PASSworrd
Accept: 'application/json',
'Content-Type': 'application/json'
},
})
.then((response) => response.json())
.then((responseJson) => {
// Response will here
})
.catch((error) => {
alert(error);
});
I am using http calls to call a cloud function.
I have a URL in the form
url: 'https://api.shipengine.com/v1/labels/rates/rateid,
Now I need to pass values dynamically in rated whenever the function call happens.
How to pass the value into that URL.
I am attaching my cloud function too.
exports.shipmentlabelwithreturnid = functions.https.onRequest((req, res) => {
var request = require("request");
var rateid = req.body.RateId;
console.log(rateid);
var options = { method: 'POST',
url: 'https://api.shipengine.com/v1/labels/rates/'+ rateid,
headers:
{ 'content-type': 'application/json',
accept: 'application/json'
}
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
});
You should use promises, in your Cloud Function, to handle asynchronous tasks. By default request does not return promises, so you need to use an interface wrapper for request, like request-promise which "returns a regular Promises/A+ compliant promise", as follows:
....
const rp = require('request-promise');
exports.shipmentlabelwithreturnid = functions.https.onRequest((req, res) => {
var rateid = req.body.RateId;
console.log(rateid);
var options = { method: 'POST',
uri: 'https://api.shipengine.com/v1/labels/rates/'+ rateid,
headers:
{ 'content-type': 'application/json',
accept: 'application/json'
}
};
rp(options)
.then(response => {
console.log('Get response: ' + response.statusCode);
res.send('Success');
})
.catch(err => {
// API call failed...
res.status(500).send('Error': err);
});
});
Also, it is important to note that you need to be on the "Flame" or "Blaze" pricing plan.
As a matter of fact, the free "Spark" plan "allows outbound network requests only to Google-owned services". See https://firebase.google.com/pricing/ (hover your mouse n the question mark situated after the "Cloud Functions" title)
Since https://api.shipengine.com is not a Google-owned service, you need to switch to the "Flame" or "Blaze" plan.
On the fact that you have to use promises to handle asynchronous tasks, I suggest that you watch these videos from the Firebase team: https://www.youtube.com/watch?v=7IkUgCLr5oA&t=28s and https://www.youtube.com/watch?v=652XeeKNHSk which explain this key concept.
I know there many answers regarding to this question but I can't seem to find one that works for me. I'm sending a post request to my server using axios but it does not work in android although it does in ios. I'm currently using server ip address (not localhost), and I'm also sending headers when request but it is still not going through the network request for android.
import axios from 'axios';
const SERVER_URL = 'http://serverip:3000';
export function signin({ username, password }) {
return function(dispatch) {
axios.post(`${SERVER_URL}/user/authenticate`, { username, password }, { headers: { 'Content-Type': 'application/json' } })
.then((response) => {
console.log('login response', response);
dispatch({
type: USER_AUTH,
});
AsyncStorage.setItem('token', response.data.token || '');
})
.catch((response) => console.log('user sign in err', response));
};
}
Has anyone had similar issue like myself and know how to make this work?
Thank you,
Set header to
headers: {
Accept: 'application/json',
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
},
I have a react native app that posts and gets data from a remote server. In post, i need to include csrf token to avoid token mismatch errors. This is the backend laravel method
//Android Login
public function androidLogin(){
return response()->json([
'name' => 'Android Login',
'route' => 'androidLogin'
]);
}
This is the react native code(i have stripped out error catching code).
async handleSubmit(){
var me = this.state.message;
console.log('this connected',me);
let response = await fetch('http://not-brusselus.be/androidLogin', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-CSRF-TOKEN':'csrf_field()'
},
body: JSON.stringify({
session:{
email: 'chesterfield#gmail.com',
password: '123456',
}
})
});
//let res = await response.text();
if (true) {
console.log(response);
} else {
//Handle error
//let error = res;
//throw error;
}
}
The response shows laravel's token mismatch page. How can i send the csrf token successfully?.
Hang the CSRF token off of the window as defined in your main laravel layout file:
window.Laravel = {
csrfToken: '{{csrf_token()}}'
}
Then just use that in your javascript requests:
...window.Laravel.csrfToken
Edit
To the downvoter: This is literally how Laravel does it out of the box and recommends you do it as well.