React-native converting synchronous GET api call to asynchronous GET - asynchronous

I'm trying to make a synhronous api call in my code and react-native doesn't allow that. I tried using fetch asynchronously but I get a 'network request failed' error. Here is the code I'm trying to convert:
var adfsUrl = null;
var req = new XMLHttpRequest();
req.open('GET', url + '/XrmServices/2011/Organization.svc?wsdl=wsdl0', true);
req.setRequestHeader('Connection', 'Keep-Alive');
req.setRequestHeader('Content-Type', 'application/soap+xml; charset=UTF-8');
req.onreadystatechange = function () {
if (req.readyState === 4) {
if (req.status === 200) {
adfsUrl = $(req.response).find('ms-xrm\\:Identifier');
}
}
};
return $(adfsUrl[0]).text().replace("http://", "https://");
My failed attempt code:
var adfsUrl = null;
try {
let response = await fetch(url + '/XrmServices/2011/Organization.svc?wsdl=wsdl0',
{
method: 'GET',
headers: {
'Connection': 'Keep-Alive',
'Accept': 'application/json',
'Content-Type': 'application/soap+xml; charset=UTF-8',
},
});
let responseJson = await response.json();
adfsUrl = $(responseJson).find('ms-xrm\\:Identifier');
return $(adfsUrl[0]).text().replace("http://", "https://");
} catch(error) {
console.error(error);
}

Related

use state to build url query string

I am new to Redux, so any help would be appreciated.
I want to add a variable to my fetch GET request URL inside the action creator.
yourapi.com/getuser/{user1}
I might not be following the correct process, I am very new to redux. I am using NextJS with React-Redux for this project.
My action:
// Get User Object
export const load_user = () => async dispatch => {
try {
const res = await fetch(`/api/getuser`, {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
});
const data = await res.json();
if (res.status === 200) {
dispatch({
type: LOAD_USER_SUCCESS,
payload: data
});
} else {
dispatch({
type: LOAD_USER_FAIL
});
}
} catch(err) {
dispatch({
type: LOAD_USER_FAIL
});
}
};
That part seems ok.
In this getuser.js file, the action calls (The action creator) how do I append a username variable onto the URL ${API_URL}/GetUser/{username} ?
export default async (req, res) => {
if (req.method === 'GET') {
const username = ??????????
try {
// How to get username???
const apiRes = await fetch(`${API_URL}/GetUser/username`, {
method: 'GET',
headers: {
'Accept': 'application/json',
}
});
const data = await apiRes.json();
if (apiRes.status === 200) {
return res.status(200).json({
user: data
});
} else {
return res.status(apiRes.status).json({
error: data.error
});
}
} catch(err) {
return res.status(500).json({
error: 'Something went wrong when retrieving user'
});
}
} else {
// Error. Not a GET request. They tried POST or PUT etc.
res.setHeader('Allow', ['GET']);
return res.status(405).json({
error: `Method ${req.method} not allowed`
});
}
};
I tried
const user = useSelector(state => state.user)
but I get the error
Invalid hook call error - TypeError: Cannot read properties of null (reading 'useContext')

axios firebase refresh token authorization header not override

I'm trying to refresh token(firebase) in react native without success. It add the new token but in this way
Authorization Bearer old_token, Bearer new_token
Expected behaviour
Authorization Bearer new_token
Here is my code, we can see the instance, interceptor for append current token to all request and finally the interceptor for the refresh token. I don't know what I'm missing.
const customConfig: AxiosRequestConfig = {
baseURL: 'http://localhost:3000',
headers: {
'content-type': 'application/json',
},
responseType: 'json',
};
const instance: any = axios.create(
customConfig,
);
// interceptor to put token to all request
instance.interceptors.request.use(
async (config: any) => {
const token = await AsyncStorage.getItem('token');
if (token) {
config.headers.authorization = 'Bearer ' + token;
console.log("config.headers.authorization", config.headers.authorization)
}
return config;
},
(error: any) => {
Promise.reject(error);
},
);
// interceptor to handle refresh token
instance.interceptors.response.use((response: any) => {
return response;
},
function (error: any) {
console.log("error en axios", error)
const originalRequest = error.config;
if (!error.response) {
return Promise.reject('Network Error');
}
if ((error.response.status === 401) && !originalRequest._retry) {
originalRequest._retry = true;
return firebase.auth().currentUser?.getIdTokenResult(false).then((res) => {
AppStorage.setToken(res.token).then(() => { console.log('Token saved'); });
const addToken = 'Bearer ' + res.token;
instance.defaults.headers.common['Authorization'] = addToken;
originalRequest.headers['Authorization'] = addToken;
return axios(originalRequest);
});
}
return Promise.reject(error);
},
);

Flutter : Edit profile returns 401 'Unauthenticated' but works in POSTMAN

i was trying to edit my user's profile with flutter and laravel based on this tutorial . My register and login works fine. However, when i try to edit it always return this error.
Here are some of my codes;
api.dart
class CallApi {
final String _url = 'http://10.0.2.2:8000/api/';
var token ;
postData(data, apiUrl) async {
var fullUrl = _url + apiUrl + await _getToken();
print(fullUrl);
return await http.post(
fullUrl,
body: jsonEncode(data),
headers: _setHeaders());
}
editData(data, apiUrl) async {
var fullUrl = _url + apiUrl + await _getToken();
return await http.post(
fullUrl,
body: jsonEncode(data),
headers: _setTokenHeaders())
.then((response) {
print('Response status : ${response.statusCode}');
print('Response body : ${response.body}');
});
}
getData(apiUrl) async {
var fullUrl = _url + apiUrl + await _getToken();
return await http.get(fullUrl, headers: _setHeaders());
}
_setHeaders() => {
'Content-type': 'application/json',
'Accept': 'application/json',
};
_getToken() async {
SharedPreferences localStorage = await SharedPreferences.getInstance();
var token = localStorage.getString('token');
return '?token=$token';
}
_setTokenHeaders() =>
{
'Content-type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer $_getToken()',
};
}
Handle update function
void _handleUpdate() async {
setState(() {
_isLoading = true;
});
var data = {
'residency': locationController.text,
'spouse': spouseController.text,
'occupation': occupationController.text,
};
var res = await CallApi().postData(data, 'profile');
// i've tried both postData and editData which returns the same error
var body = json.decode(res.body);
print(body);
/*if (body['status'] == true) {
SharedPreferences localStorage = await SharedPreferences.getInstance();
localStorage.setString('user_details', json.encode(body['token']));
Navigator.of(context).pushNamed(Profile.tag);
}*/
}
Logcat
I/flutter ( 2390): {message: Unauthenticated.}
The api works properly through postman and i have checked the url and parameters which i am entering in the post request and they are the same as that of postman but still i keep getting the error.
Whats working on POSTMAN
Register
Login
Logout
Update
On flutter App
Register
Login
You should only return the token only. No need to return string query.
_getToken() async {
...
return token;
};
Also, remove the _getToken() from your fullUrl variable. You need to send the token by headers, not by query parameters.
EDITED
Your postData() function should be using _setTokenHeaders() in the headers instead.

Http post in angular 7 returns invalid response

I am using http post for one of my angular application for login.I have checked the url with the params in postman which gives me the output.But when i try to use the same in the application i am getting the error as invalid login all the time.
I would like to know whether the way i pass the params are correct or not?
const formData = `username=${username}&password=${password}`;
const options = { headers: new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' }) };
return this.http.post<any>(`${this.baseUrl}?action=login&`, formData, options)
.pipe(map(response => {
console.log('user is', response);
if (response && response.session && response.session.id) {
localStorage.setItem('currentUser', JSON.stringify(response));
this.currentUserSubject.next(response);
}
return response;
}));
The error i am getting is
user is {error: "Incorrect Login."}
You can try like this instead of formData
const data = new HttpParams()
.set('username', username)
.set('password', password);
return this.http.post<any>(`${this.baseUrl}?action=login&`, data)
.pipe(map(response => {
if (response.status === 'success') {
localStorage.setItem('currentUser', JSON.stringify(response));
this.currentUserSubject.next(response);
}
return response;
}));

Angular 2 http Post failing on client side but data is getting inserted in the Database

Service
The HTTP post service
addUser(body: Object): Observable<any> {
let bodyString = JSON.stringify(body);
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.post(this.baseUrl + 'api/v3/user/Adduser', body, options)
.map((res: Response) => res.json())
.catch((error: any) => Observable.throw(error.json().error || 'Server error'));
}
Component
When I call this method, the data is getting inserted into the database, but I am unable to get the response. It is going into the error block. Please look at the image below for error information.
addUser(items: any) {
this.signupService.addUser(items)
.subscribe(response => {
this.eventsEmitter.broadcast('Success', 'Changes Saved Succesfully');
this.router.navigate(['/login']);
},
error => {
debugger;
this.eventsEmitter.broadcast('Error', 'Error Occured');
});
}
Error Information
Not sure how to resolve this. Can you please tell me the changes to make it work?
Web API Controller
This is the web API controller
[HttpPost]
[Route("AddUser")]
public async Task<IHttpActionResult> AddUser([FromBody]UsersModel model)
{
try
{
await _userService.AddUser(model);
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.Created);
return ResponseMessage(response);
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
Try to do the following changes :
addUser(items: any) {
this.signupService.addUser(items)
.subscribe(response => {
this.eventsEmitter.broadcast('Success', 'Changes Saved Succesfully');
this.router.navigate(['/login']);
});
}
Web API Controller :
[HttpPost]
[Route("AddUser")]
public async Task<IHttpActionResult> AddUser([FromBody]UsersModel model)
{
try
{
await _userService.AddUser(model);
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
return ResponseMessage(response);
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
Http Service :
addUser(body: Object): Observable<any> {
let bodyString = JSON.stringify(body);
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.post(this.baseUrl + 'api/v3/user/Adduser', body, options)
.map((response : Response) => {
if (response.status < 200 || response.status >= 300) {
throw new Error('This request has failed ' + response.status);
}
else {
return response.json();
}
});
}
Make sure you import the necessary dependencies:
import { Observable } from "rxjs/Observable";
import 'rxjs/add/observable/throw';

Resources