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

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

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";
};

axios post / get always return 404 in react

// Login Method
const postLogin = (url, data) => {
return axios.post(url, data).then(response => {
if (response.status === 400 || response.status === 500)
throw response.data;
console.log(response);
return response;
}).catch(err => {
console.log(err);
throw err[1];
});
}
The above login method always log the following error:
Error: Request failed with status code 404
at createAxiosError (utils.js:147:1)
at Object.settle (utils.js:123:1)
at handleRequest (handle_request.js:124:1)
at index.js:26:1
at new Promise (<anonymous>)
at MockAdapter.<anonymous> (index.js:25:1)
at dispatchRequest (dispatchRequest.js:52:1)
On call
const response = yield call(postLogin, 'http://localhost:8080/users/verify_login/', {
email: user.username,
password: user.password,
headers: {
"Content-Type": "application/json",
"accept" : "application/json",
}});
Though the http://localhost:8080 is running. We are using React. How to solve this?
You can try using async await for better debugging your code.
const postLogin = async (url, data) => {
try{
var response = await axios.post(url, data)
return response
}catch(e){
// Handle catch
}finally{
// Handle finally
}
}

React axios response -> Authorization value does not appear in the header

It's my Api Code.
There is no Authorization in the response header, but if you look at the header in the Network window, it exists.
I would appreciate it if you could help me figure out what the problem is and how to solve it.
const onLogin = async (event) => {
event.preventDefault();
var encrypt = new JSEncrypt();
encrypt.setPublicKey(REACT_APP_ENC_PUB_KEY);
let encryptedPassword = encrypt.encrypt(password);
try {
let res = await axios.post(
`http://xx.xx/api/v1/users/login`,
{
id: email,
password: encryptedPassword,
},
{
headers: {
Accept: 'application/json',
'Content-type': 'Application/json',
withCredentials : true
},
},
)};
catch (err) {
console.log(err);
let errmsg = err.response.data.message;
setErrMsg(errmsg);
}
};
console axios response header
Network axios response header

In React while submitting a sign in, am getting my password and email in (Localhost)URL as query string?

After running my project in Localhost and and giving my information's for signin , am getting this in my URL
http://localhost:3000/?email-address=roopa%40gmail.com&password=roopa3
and i also checked for "onClick" in my events, but everything is ok..
event.preventDefault();
console.log('emailchanged')
this.setState({signinEmail: event.target.value})
}
onPasswordchange = (event) => {
event.preventDefault();
console.log('passwordchanged')
this.setState({signinPassword: event.target.value})
}
onSubmitSignin = () => {
console.log('entered onsubmitsignin..') // after this console msg again my localhost redirects me to a new signin page which giving inputs to URL as query strings
fetch('http://localhost:8050/signinpage/', {
method: 'post',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
email: this.state.signinEmail,
password: this.state.signinPassword
})
})
.then(function (response) {
console.log(response.status);
return response.json();
})
.then(res => {
if(res.ok){
this.props.onRoutechange('Home');
}
else if (!res.ok) {
throw new Error("HTTP status " + res.status);
}
})
}
I don't need my inputs to show as query string here..!

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