why axios.postForm working instead of axios.post - reactjs

so, I try to login using API hosted in in webhost, but why my code doesn't work with axios.post and only works with axios.postForm?
what is axios.postForm? and i need to get data from the API too but it only works with axios.getUri. what is axios.getUri? I cannot use.then if I use axios.getUri
anyone can explain? thank you.
try {
const loginReq = await axios.postForm(
"http://spdaapp.000webhostapp.com/api/auth/login",
{
headers: {
"Content-Type": "application/json",
accept: "*/*",
},
username: field.username,
password: field.password,
}
);
const loginResp = await loginReq.data;
setLoading(false);
if (loginReq.status === 200) {
console.log(field.username);
console.log(loginResp);
Cookie.set("token", loginResp.access_token);
Cookie.set("role", loginResp.status);
router.push("/admin/dashboard");
}
} catch (error) {
const err = error as AxiosError;
// console.log(err.response?.status);
// console.log(err.response?.data);
setLoading(false);
setShowSnackbar(true);
}
}

Related

ReactJS - Fetch returns undefined on device (chrome)

English is not my main language so I will try to explain myself (sorry).
I have a website developed in ReactJS that works perfectly on a subdomain called "test": https://test.mydomain.com
All the URL's that call the api point to another subdomain called "api", for example: https://api.mydomain.com
In the desktop browser it works perfectly. But when I test in the device's browser (Chrome) the api always returns "undefined".
I copy part of my code:
At https://test.mydomain.com:
const myFuction= async() => {
try {
const API_ENDPOINT = `https://api.mydomain.com/users.php`;
const data = await fetch(API_ENDPOINT, {
method: "POST",
headers: {
Accept: "application/json",
"Content-type": "application/json",
},
body: JSON.stringify({
param1: "PARAM_1",
}),
});
const users = data.json();
if (users.result.user != undefined) {
console.log("Token OK");
return true;
} else {
console.log("Token ERROR.");
return false;
}
} catch (error) {
alert(error);
console.error(error);
}
return "ERROR";
};
Could you help me? I've been trying to figure it out for days.
Thanks!
I solved the problem with the help of #punjira. The error was from CORS.
To solve it I had to add this line in the backend response:
header('Access-Control-Allow-Origin: *');
And I commented the headers that I sent in the request, the function looks like this:
const myFuction= async() => {
try {
const API_ENDPOINT = `https://api.mydomain.com/users.php`;
const data = await fetch(API_ENDPOINT, {
method: "POST",
// headers: {
// Accept: "application/json",
// "Content-type": "application/json",
// },
body: JSON.stringify({
param1: "PARAM_1",
}),
});
const users = data.json();
if (users.result.user != undefined) {
console.log("Token OK");
return true;
} else {
console.log("Token ERROR.");
return false;
}
} catch (error) {
alert(error);
console.error(error);
}
return "ERROR";
};

how to fix warning possible Unhandled promise rejection (id 0) react native

this warning show in emulator
this warning show in console
and here my code how to fix this problem
CreateAdmin = (credentials) => {
console.log('im here');
try{
fetch("api/url", {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json"
},
body: JSON.stringify(credentials)
}).then(data => data.json());
} catch{
console.log("Api call error");
}
}
handleCreateAdmin = async () => {
console.log('stay here handleCreateAdmin');
const displayName = this.state.displayName;
const username = this.state.username;
const password = this.state.password;
const response = await CreateAdmin({
displayName,
username,
password
});
console.log(displayName,username,password);
console.log(response);
if(response.success){
alert("success");
}
}
and the second question is How can I send the image to the api and store the image in the database and display it back in the front-end? like message chat thank for help

How do I create a Generic postToAPI(route, package2send) function in React?

In our project we are using the MERN stack
I want to create a generic function whose input is the path to any api endpoint in our server and the JSON package to POST to the server. I want it to return the JSON sent back from the server.
That way when we are developing our mobile app and web app, we can simply use this function for all of our api endpoint POSTs.
I'm very new to using React/React-Native so I'm sure that I'm not understanding some sort of key concept.
Here is what I have so far:
import React from 'react';
// returns whatever the respective apiEndpoint is suppose to return
function postToAPI(route, package2send)
{
async() =>
{
try
{
const payload = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: package2send
}
const res = await fetch(route, payload);
console.log(res);
const data = await response.json();
console.log(data);
return data;
}
catch(error)
{
console.error(error);
}
}
}
export default postToAPI;
Whenever I call this function from my Login.js after I
import { postToAPI } from './postToAPI'
I get this error: 'TypeError: Object(...) is not a function'
I'm sure there are multiple things wrong with this code, so if someone could steer me in the right direction, it would be greatly appreciated.
If you export the function as default, you must import without bracket like that.
import postToAPI from './postToAPI';
If you would like to write a generic API call class, I advise you this class which I wrote before.
import { BASE_URL } from "../config";
import { Actions } from "react-native-router-flux";
import { deleteUserInfo } from "./SessionHelper";
const API_URL = BASE_URL;
class ApiHelper {
private accessToken?: string;
constructor() {
this.accessToken = undefined;
}
setAccessToken = (accessToken: string) => {
this.accessToken = accessToken;
};
getAccessToken = () => {
return this.accessToken;
};
getRequest = async (endpoint: string) => {
try {
const response = await fetch(`${API_URL}${endpoint}`, {
method: "GET",
headers: {
"x-access-token": `${this.accessToken}`
}
});
const responseJson = await response.json();
return responseJson;
} catch (error) {
console.error(error);
}
};
postRequest = async (endpoint: string, body: any) => {
try {
const response = await fetch(`${API_URL}${endpoint}`, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
"x-access-token": `${this.accessToken}`
},
body: JSON.stringify(body)
});
const responseJson = await response.json();
const finalResponse = { data: responseJson, status: response.status };
if (response.status === 401) {
deleteUserInfo();
this.accessToken = undefined;
Actions.auth();
}
return finalResponse;
} catch (error) {
console.error(error);
return error;
}
};
patchRequest = async (endpoint: string, body: any) => {
try {
const response = await fetch(`${API_URL}/${endpoint}`, {
method: "PATCH",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
"x-access-token": `${this.accessToken}`
},
body: JSON.stringify(body)
});
const responseJson = await response.json();
const finalResponse = { data: responseJson, status: response.status };
if (response.status === 401) {
deleteUserInfo();
this.accessToken = undefined;
Actions.auth();
}
return finalResponse;
} catch (error) {
console.error(error);
}
};
deleteRequest = async (endpoint: string, body: any) => {
try {
const response = await fetch(`${API_URL}/${endpoint}`, {
method: "DELETE",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
"x-access-token": `${this.accessToken}`
},
body: JSON.stringify(body)
});
const responseJson = await response.json();
const finalResponse = { data: responseJson, status: response.status };
if (response.status === 401) {
deleteUserInfo();
this.accessToken = undefined;
Actions.auth();
}
return finalResponse;
} catch (error) {
console.error(error);
}
};
}
export const APIHelper = new ApiHelper();

Error: Cannot read property 'token' of undefined

I have a function api inside the method onSubmit, which make request to the server:
onSubmit: async (formValues) => {
setSubmitting(true);
try {
const res = await api('api/auth/register', {
method:'POST',
body: JSON.stringify(formValues)
});
if(Array.isArray(res)){
setErrorMessage(res[0].message);
} else {
const token = res.token.token;
localStorage.setItem('myToken', token);
history.push("/home");
}
} catch(e) {
console.error(e);
} finally {
setSubmitting(false);
}
},
});
Function api is in a separate file and looks like this:
export const api = async (url, args) => {
const response = await fetch(`${apiUrl}${url}`, {
...args,
headers: {
"Content-type": "application/json; charset=UTF-8 ",
"Accept": 'application/json',
...args.headers,
},
});
return response.json();
}
This function was created simply for convenience. But now I dont need this function. I need that code from api was inside method onSubmit. That is, that the function api not exist at all.
And I did it:
onSubmit: async (formValues) => {
setSubmitting(true);
try {
const resf = await fetch(`${apiUrl}api/auth/register`, {
method:'POST',
body: JSON.stringify(formValues),
headers: {
"Content-type": "application/json; charset=UTF-8 ",
"Accept": 'application/json',
}
});
const res = resf.json();
if (Array.isArray(res)){
setErrorMessage(res[0].message);
} else {
const token = res.token.token;
localStorage.setItem('myToken', token);
history.push("/home");
}
} catch(e) {
console.error(e);
} finally {
setSubmitting(false);
}
},
});
But I have error:
TypeError: Cannot read property 'token' of undefined
Why is this error occurring?
Try with await for resf.json() because calling .json() gets you another promise for the body of the http response that is yet to be loaded.
const res = await resf.json();

axios.post returns bad request of 400 React Native

I'm getting my token from an API but unfortunately my API is returning 400 bad request. I've already checked my api via Postman and it's working fine there. Kindly let me know solution or any mistake.
async componentWillMount(){
axios.post('http://api.myapiurl.com/token', {
grant_type: 'PASSWORD',
username: 'MY_USERNAME',
password: 'MY_PASSWORD'
}, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
}).then(response => {
console.log(response.data)
}).catch(err => console.log("api Erorr: ", err.message))
}
error in response below
Request failed with status code 400
- node_modules\axios\lib\core\createError.js:16:24 in createError
- node_modules\axios\lib\core\settle.js:18:6 in settle
- ... 10 more stack frames from framework internals
It is Solved by using QueryString.stringify(). I just pass the body into QueryString.stringify() like below:
axios.post('http://api.apiurl.com/token', QueryString.stringify({
grant_type: 'MY_GRANT_TYPE',
username: 'MY_USERNAME',
password: 'MY_PASSWORD'
}), {
headers: {
"Content-Type": "application/x-www-form-urlencoded",
}
}).then(response => {
console.log(response.data)
}).catch(err => console.log("api Erorr: ", err.response))
From what I can see you are sending json data, but your Content-Type header is set to application/x-www-form-urlencoded; charset=UTF-8. if your api is expecting json then it should be application/json.
try using fetch instead, might be some axios bug, you dont need to add any libraries, here is an example:
fetch("http://api.myapiurl.com/token", {
method: "POST", // *GET, POST, PUT, DELETE, etc.
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
grant_type: "PASSWORD",
username: "MY_USERNAME",
password: "MY_PASSWORD"
})
})
.then(res => {
res.json();
})
.then(data => console.log(data)) // ur data is here
.catch(err => console.log("api Erorr: ", err));
First install the package axios from the url https://www.npmjs.com/package/react-native-axios
Then create two service for handling get and post request so that you can reuse them
GetService.js
import axios from 'axios';
let constant = {
baseurl:'https://www.sampleurl.com/'
};
let config = {
headers: {
'Content-Type': 'multipart/form-data',
'Accept': 'application/json'
}
};
export const GetService = (data,Path,jwtKey) => {
if(jwtKey != ''){
axios.defaults.headers.common['Authorization'] = 'Bearer '+jwtKey;
}
try{
return axios.get(
constant.baseUrl+'api/'+Path,
data,
config
);
}catch(error){
console.warn(error);
}
}
PostService.js
import axios from 'axios';
let constant = {
baseurl:'https://www.sampleurl.com/'
};
let config = {
headers: {
'Content-Type': 'multipart/form-data',
'Accept': 'application/json'
}
};
export const PostService = (data,Path,jwtKey) => {
if(jwtKey != ''){
axios.defaults.headers.common['Authorization'] = 'Bearer '+jwtKey;
}
try{
return axios.post(
constant.baseUrl+'api/'+Path,
data,
config
);
}catch(error){
console.warn(error);
}
}
Sample code for using get and post services is given below
import { PostService } from './PostService';
import { GetService } from './GetService';
let uploadData = new FormData();
uploadData.append('key1', this.state.value1);
uploadData.append('key2', this.state.value2);
//uploadData.append('uploads', { type: data.mime, uri: data.path, name: "samples" });
let jwtKey = ''; // Authentication key can be added here
PostService(uploadData, 'postUser.php', jwtKey).then((resp) => {
this.setState({ uploading: false });
// resp.data will contain json data from server
}).catch(err => {
// handle error here
});
GetService({}, 'getUser.php?uid='+uid, jwtKey).then((resp) => {
// resp.data will contain json data from server
}).catch(err => {
// handle error here
});
Reference from one of my another post Post action API with object parameter within the URL
If you have any doubts, feel free to know

Resources