TypeError: Network request failed - I get this error when I try to log in what is the solution to my problem here is the code that I use and thank you
constructor(props)
{
super(props)
this.state={email1:'',password1:''}
}
login = () =>
{
const {email1}=this.state;
const {password1}=this.state;
fetch('http://192.168.1.114',{
method: 'POST',
headers:{
'Accept': 'application/json',
'Content-Type':'application/json'
},
body: JSON.stringify({
email: 'email1',
password: 'password1'
})
})
.then((response)=>response.json())
.then((responseJson)=>{
alert(responseJson)
})
.catch((error)=>{
console.error(error);
});
Related
I have used Axios for API call in react native but get result Network Error.
const config = {
method: 'post',
url: BASE_URL+"/auth/login",
headers: {
'Content-Type': 'application/json',
},
data: {
username: "physician#doral.com",
password: "password",
device_token: "",
device_type: 1,
latitude: "",
longitude: ""
}
};
axios(config)
.then((response) => {
console.log(response);
})
.catch((err) => {
console.log("err :", err);
Alert.alert("something went to wrong.",err.message);
});
I had use above axios function but get network error in react native. how to fix network error in react native Application.
$Happy New Year! So, I'm setting up a redirect after an authentication token retrieval and I keep getting "TypeError: Cannot read properties of undefined (reading '$router')" in the console and the user is not redirected to the desired page ("/dashboard"). I'm outsourcing the authentication to a dataRequests.user.js file that then goes to a vue component. Thanks in advance. Here is the code:
import common from "./dataRequests.commons";
import { login, inputLogin, inputPassword } from '/src/pages/Index.vue'
let userRequest = {}
userRequest.authenticate = (inputLogin, inputPassword) => {
return new Promise(() => {
let axios = require("axios");
let config = {
method: 'post',
baseURL: common.baseURL + '/auth/login',
headers: {
'Content-Type': 'application/json',
},
data : {
login: inputLogin,
password: inputPassword,
}
};
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.then(() => this.$router.push(this.$router.redirect || '/dashboard'))
.catch(function (error) {
console.log(error);
//console.log('input login', this.inputLogin)
//console.log('input password', this.inputPassword)
});
console.log('input login', inputLogin)
console.log('input password', inputPassword)
});
}
export default userRequest;
Something like this:
import common from "./dataRequests.commons";
import { login, inputLogin, inputPassword } from '/src/pages/Index.vue'
import axios from 'axios'
import router from 'router'
let config = {
method: 'post',
baseURL: common.baseURL + '/auth/login',
headers: {
'Content-Type': 'application/json',
}
userRequest.authenticate = (inputLogin, inputPassword) => {
const apiClient = axios.create(config)
return new Promise(() => {
apiClient.post(data : {
login: inputLogin,
password: inputPassword,
})
.then(() => router.push...etc
Question:
How can we get post data from fetch function in react native to express api?
Issue Faced:
I tried the following process but didn't got those variables in back-end API.
How can the variables be achieved in the backend API? Any suggestions are highly appreciated.
Here is the reactive native fetch function:
REACT NATIVE FETCH FUNCTION:
login = async () => {
await fetch('http://192.168.1.160:8001/api/login', {
method: 'POST',
mode: 'cors',
cache: 'default',
header: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: this.state.email,
password: this.state.password
})
})
.then ((response) => response.json())
.then ((res) => {//console.log(res);
if(res.error === false){
AsyncStorage.setItem('user', res.data);
this.props.navigation.navigate('profile');
} else{
// alert(res.message);
}
})
}
Express-API:
The express API is given below:
module.exports = function (req, res) {
console.log('TEST',req.body);
let { email, password } = req.body;
let input = { email, password };
const validator = loginValidator(input);
if (validator.error) {
return res.status(400).json({
error: true,
message: validator.error.details,
});
} else {
models.users.findOne({
where: { email: email }
}).then(user => {
if (!user) {
return res.status(400).json({
error: true,
message: {
key: 'email',
text: MessageHelper.email_already_exist
}
});
} else if (!bcrypt.compareSync(password, user.password)) {
return res.status(400).json({
error: true,
message: {
key: 'password',
text: MessageHelper.password_not_valid
}
});
} else {
var token = jwt.sign({ userid: user.id },Config.get('jwt.privatekey'));
models.users.update({ token: token },{ where: { id: user.id } }).then(function(result){
return res.json({
error: false,
message: MessageHelper.user_token_updated,
token: token,
data: {
user_id: user.id,
firstname: user.firstname,
lastname: user.lastname,
username:user.username,
email: user.email,
mobile: user.mobile,
token: user.token
}
});
}).catch(function(error){
return res.status(400).json({
error: true,
message: error
});
})
}
});
}
}
Fetch also takes an optional second argument that allows you to
customize the HTTP request. You may want to specify additional
headers, or make a POST request:
fetch('https://mywebsite.com/endpoint/', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstParam: 'yourValue',
secondParam: 'yourOtherValue',
}),
});
Networking is an inherently asynchronous operation. Fetch methods will
return a Promise that makes it straightforward to write code that
works in an asynchronous manner:
function getMoviesFromApiAsync() {
return fetch('https://facebook.github.io/react-native/movies.json')
.then((response) => response.json())
.then((responseJson) => {
return responseJson.movies;
})
.catch((error) => {
console.error(error);
});
}
I'm trying to receive a token from Spotify api. Unfortunately I keep on receiving 415. Could you help me and let me know what am I doing wrong?
const axios = require('axios');
const getToken = (code) => {
return axios({
method: 'post',
url:'https://accounts.spotify.com/api/token',
form: {
code,
grant_type :'authorization_code',
redirect_uri: process.env.SPOTIFY_REDIRECT
},
headers: {
'Authorization': 'Basic ' + (new Buffer(process.env.SPOTIFY_ID + ':' + process.env.SPOTIFY_SECRET).toString('base64')),
'Content-Type': 'application/json'
}
}).then(token => {
return token;
}).catch(e=> {
console.log(e);
return e.response;
});
};
module.exports = {
getToken
};
415 error code is related to problem with wrong content type or content encoding, (https://httpstatuses.com/415)
I do not know axios but please take a look on the example on spotify github https://github.com/spotify/web-api-auth-examples/blob/master/authorization_code/app.js#L74
According to this issue on github (https://github.com/spotify/web-api/issues/321), try to use content-type 'Content-Type': 'application/x-www-form-urlencoded'
There is example withs axios
axios({
url: "https://accounts.spotify.com/api/token",
method: "post",
params: {
grant_type: "client_credentials"
},
headers: {
"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded"
},
auth: {
username: "YOUR-CLIENT-ID",
password: "YOUR-CLIENT-SECRET"
}
}).then(function (response) {
console.log(response);
}).catch(function (error) {
});
It works!!!
What I've done was:
- change Content-Type for 'application/x-www-form-urlencoded'
- client_id and client_secret were taken from header and posted before grant_type in body
- changed 'data' to 'params'
const axios = require('axios');
const getToken = (code) => {
return axios({
method: 'post',
url:'https://accounts.spotify.com/api/token',
params: {
client_id: process.env.SPOTIFY_ID,
client_secret: process.env.SPOTIFY_SECRET,
code,
grant_type :'authorization_code',
redirect_uri: process.env.SPOTIFY_REDIRECT
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(token => {
return token;
}).catch(e=> {
return e.response.data;
});
};
And it resulted with a beautiful looking token \m/
After spending one hour trying to figure out how to get the token, I came up with this answer! :)
const axios = require('axios');
const express = require('express');
const app = express();
const client_id= 'YOURCLIENTID';
const client_secret = 'YOURCLIENTSECRET';
app.get('/api/token', (req, res) => {
axios({
method: 'post',
url: 'https://accounts.spotify.com/api/token',
headers: {
'Authorization': 'Basic ' + (new Buffer.from(client_id + ':' + client_secret).toString('base64')),
'Content-Type': 'application/x-www-form-urlencoded'
},
params: {
grant_type: 'client_credentials'
},
json: true,
})
.then(body => {
res.send(body.data.access_token);
})
.catch(e => {
console.log(e.response.data);
});
});
app.listen(3000, () => {
console.log('Server Listening on port 3000');
});
If you making API call from client side (browser), try this solution:
getTokken() {
const urlSpotify = "https://accounts.spotify.com/api/token";
axios({
method: "post",
url: urlSpotify,
data: "grant_type=client_credentials",
headers: {
Accept: "application/json",
"Content-Type": "application/x-www-form-urlencoded",
},
auth: {
username: process.env.REACT_APP_SPTID_KEY, // User ID
password: process.env.REACT_APP_SPCS_KEY, // User Secret
},
})
.then((response) => {
console.log(response);
})
.catch((err) => console.log(err));
}
I have just tried to store an item in AsyncStorage after success
response.I have made http request using axios.I have little bit confused i tried already how to store data using AsyncStorage but when i trying to store an item on http request onSucess() is not storing.please help me where i made mistakes.
axios.post(url, { email: this.state.email, password: this.state.password } , config)
.then(function (response){
// Alert.alert("success:",JSON.stringify(response.data.token));
this.setState({ showProgress: false })
this.setState({token:JSON.stringify(response.data.token)});
var accesstoken=JSON.stringify(response.data.token);
console.log(accesstoken);
AsyncStorage.setItem("accesstoken",accesstoken);
Alert.alert("success:", accesstoken);
// Alert.alert("success:", JSON.stringify(accesstoken));
}).catch(function (error) {
Alert.alert("Error:",error);
});
Use below fetch method
fetch(url, {
method: 'POST',
headers: { 'Accept': 'application/json','Content-Type': 'application/json',},
body: JSON.stringify({ email: this.state.email, password: this.state.password})
}).then((response) => response.json())
.then((responseData) => {
// Alert.alert("success:",JSON.stringify(response.data.token));
this.setState({ showProgress: false })
this.setState({token:JSON.stringify(response.data.token)});
var accesstoken=this.state.token;
console.log(accesstoken);
AsyncStorage.setItem("accesstoken",accesstoken);
}).catch((error) => {
Toast.show("There is a Problem on your network connection");
});
Here is the example use that :
`fetch(<hostURL>, {
method: 'POST',
headers: { 'Accept': 'application/json','Content-Type': 'application/json',},
body: JSON.stringify({ email: <email> ,password: <password>})
}).then((response) => response.json())
.then((responseData) => {
if(responseData.STATUS == true){
AsyncStorage.multiSet([
["state", JSON.stringify(responseData.DATA[0])],
["country", JSON.stringify(responseData.DATA[1])]
]);
}
});`
Try this
axios.post(url, { email: this.state.email, password: this.state.password } , config)
.then(response => {
// Alert.alert("success:",JSON.stringify(response.data.token));
this.setState({ showProgress: false })
this.setState({token:JSON.stringify(response.data.token)});
var accesstoken=this.state.token;
console.log(accesstoken);
// Alert.alert("success:", JSON.stringify(accesstoken));
}).catch(error => {
Alert.alert("Error:",error);
});