Unable to fetch resource with fetch, NetworkError - javascript

I'm fetching data from my API using this. It will post email and password to my API
onSubmitSignIn = () => {
fetch('http://localhost:3001/signin', {
method: 'post',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
email: this.state.signInEmail,
password: this.state.signInPassword
})
})
.then(response => response.json())
.then(data => {
if (data === 'login success') {
this.props.onRouteChange('home');
}
})
.catch((e) => console.log(e))
};
and the request will be handled in the API by this
app.post('/signin', (req, res) => {
if (req.body.email === db.users[0].email && req.body.password === db.users[0].password) {
res.json('login success')
} else {
res.json('login fail')
}
});
This will result in TypeError: NetworkError when attempting to fetch resource.
However, if the .then are removed and the this.props.onRouteChange('home'); is added below like this
onSubmitSignIn = () => {
fetch('http://localhost:3001/signin', {
method: 'post',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
email: this.state.signInEmail,
password: this.state.signInPassword
})
})
this.props.onRouteChange('home');
};
it will work and I can log in without errors.
But, the same error will still be shown if this.props.onRouteChange('home'); is removed like this
onSubmitSignIn = () => {
fetch('http://localhost:3001/signin', {
method: 'post',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
email: this.state.signInEmail,
password: this.state.signInPassword
})
})
};
I've also double checked my API with Postman and the post request was successful.
This a odd problem for me and I'm new to javascript, please forgive me if this happens to be a careless newbie mistake. Thanks.
P.S. Please let me know if more code is needed.

Are you running the app on the same client that's hosting it? Try changing localhost to your client's LAN IP and see if that makes a difference?

Related

Response data returns undefined from asp.net web api to vue.js

currently I'm fetching data from my api to front-end. I checked and my request body is arriving to server side. But after doing things when it comes to returning the token it always returns undefined data to vue.js:
[HttpPost("login")]
public async Task<IActionResult> Login([FromBody]User user)
{
var result = await _accountRepository.LoginAsync(user.username, user.password);
if (string.IsNullOrEmpty(result))
{
return Unauthorized(result);
}
Debug.WriteLine(result.ToString()); // this works and I can see the token
return Ok(result);
}
When it comes here:
methods: {
login() {
fetch("http://localhost:60427/api/account/login", {
method: "POST",
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({
username: this.username,
password: this.password,
})
}).then(response => {
console.log(response.data); // this is always undefined
})
.catch(e => {
console.log(e);
});
},
}
Please help I can't see any errors here. I'm confused.
You need to call either Response.text() or Response.json() depending on what data you expect. These methods return a Promise that resolves to the data.
E.g. for JSON:
fetch("http://localhost:60427/api/account/login", {
method: "POST",
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({
username: this.username,
password: this.password,
})
})
.then(response => response.json())
.then(data => console.log(data))
.catch(e => console.error(e));

how to use headers in fetch on React-Native or Expo

I want to communicate with the server.
In order to communicate with the server, two items must be added to headers.
Note: The key value written is not the actual key value.
api_key: "abcdegeg123456842536ebebeb1yeyju",
game_key: "abcdegeg123456842536ebebeb1yeyju"
The code I tried to communicate with:
checkNickName = async () => {
fetch("http://192.168.0.44:11000/v1/point/auth/change_nickname", {
method: "POST",
body: JSON.stringify({
wallet_address: "0f8751828af26816ef996c37e611b945304a6e99",
new_nickname: this.state.nickname
}),
headers: {
// "Content-Type": "application/json"
api_key: "abcdegeg123456842536ebebeb1yeyju",
game_key: "abcdegeg123456842536ebebeb1yeyju"
}
})
.then(res => res.json())
.then(response => {
console.log("response:" + response);
console.log(response.resultCode);
if (response.resultCode == "S000") {
Alert.alert("info","scess");
} else alert(response.result);
})
//console.log("Success:", JSON.stringify(response))
.catch(error => console.error("Error:", error));
};
But this is not working
Error:, [TypeError: Network request failed]
How can I communicate with the server? Is there another way?
thank you in advance
It was a mistake in my address,
but the server receiving the data says the data is null. How can we solve the problem?
I solved it by using formdata.
usePage.js
async checkNickName() {
let formdata = new FormData();
formdata.append(
"wallet_address",
"gBx0f8751828af26816ef996c37e611b945304a6e99"
);
formdata.append("new_nickname", this.state.nickname);
fetch("http://192.168.0.26:11000/v1/point/auth/change_nickname", {
method: "POST",
body: formdata,
headers: {
"Content-Type": "multipart/form-data",
api_key: "5b95576338b1eb1c53a1ae3f904dc7c5",
game_key: "bf61b73dd871c2973188706d813002c2"
}
})
.then(res => res.json())
.then(response => {
console.log(response);
console.log(response.resultCode);
if (response.resultCode == "S002") {
AsyncStorage.setItem("gbrickobj", this.state.gbrickobj);
AsyncStorage.setItem("nickname", this.state.nickname);
this.props.navigation.navigate("RegisterSecurity");
} else if (response.resultCode == "S001") {
this.setState({
checknick: "this nickname already use nickname."
});
} else {
Alert.alert("info", "check address.");
}
})
.catch(error => console.error("Error:", error));
}

React fetch('http://localhost:3000/profile/:id')

as the title says, I am trying to fetch this URL from node/express server. The route is working fine in Postman, so I believe it tells me the mistake is in my fetch method.
my code:
onSubmitSave = () => {
fetch('http://localhost:3000/profile/:id', {
method: 'put',
headers: {'Content-Type': 'application/json' },
body: JSON.stringify({
name: this.state.name,
telephone: this.state.telephone,
})
})
.then(response => response.json())
.then(user => {
console.log(user);
}).catch(err => console.log(err))
}
I would be glad if anyone could help me with that.
I don't see your :id being replaced by any string interpolation. You might be looking for something like this:
fetch(`http://localhost:3000/profile/${this.id}`)

Getting different json response when using fetch react native

I have a react app which calls an API when the user clicks login. However, the response that react native receives is different than the intended response.
React Native code:
login() {
this.setState({isLoading: true})
return fetch(process.env.API_USER + "/signin", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({
username: this.state.username,
password: this.state.password
})
}).then((response) => {
console.log(`\n\n\n\nRESPONSE---->${JSON.stringify(response)}\n\n\n\n`)
this.setState({isLoading: false})
})
.catch((error) => {
console.log((`\n\n\n\nERROR---->${error}\n\n\n\n`))
this.setState({isLoading: false})
})
}
Console response:
RESPONSE---->{"type":"default","status":401,"ok":false,"headers":{"map":{"via":"1.1 vegur","date":"Thu, 27 Sep 2018 18:10:42 GMT","server":"Cowboy","etag":"W/\"17-wIxJlIRlPQbTEtBjbmLpTqPMWNo\"","connection":"keep-alive","cache-control":"public, max-age=0","x-powered-by":"Express","content-length":"23","access-control-allow-credentials":"true","access-control-allow-origin":"*","access-control-allow-methods":"*","access-control-allow-headers":"Origin, Accept,Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers","content-type":"application/json; charset=utf-8"}},"url":"abc.com","_bodyInit":{"_data":{"size":23,"offset":0,"blobId":"f4012672-62b8-4b52-be6f-06446874981c"}},"_bodyBlob":{"_data":{"size":23,"offset":0,"blobId":"f4012672-62b8-4b52-be6f-06446874981c"}}}
expected API response:
RESPONSE---->{"message": "Auth Fail"}
// ----------OR---------- //
RESPONSE---->{"message": "Auth Successfull"}
As the previous answers have noted, the response object has a .json() function which returns a promise (which resolves to the actual data).
Also you can structure the code much better with async/await
login = async () => {
const options = {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({
username: this.state.username,
password: this.state.password
}),
};
this.setState({isLoading: true});
try {
const response = await fetch(`${process.env.API_USER}/signin`, options);
const responseData = await response.json(); // This is what you're missing
this.setState({isLoading: false});
} catch (error) {
// Do something about the error
console.log((`\n\n\n\nERROR---->${error}\n\n\n\n`));
}
}
In document basic structure of fetch request defined here. from the document, you can try this one
.then((response) => response.json())
.then((resJSON) => {
console(resJSON);
this.setState({isLoading: false})
})
.catch((error) => {
console.log(error)
this.setState({isLoading: false})
})
You need to have another .then that will resolve the response and converts it into JSON:
.then(response => response.json())
.then(data => {
// now you can get your server response
console.log(data)
})

React Redux Fetch action returning "415 (Unsupported Media Type)" and "401 (unauthorized)"

I have an action that creates a fetch to POST a client back to the API.
I send a JWT in the "headers" which by itself is not the problem as its also used in a GET that works just fine... but not in a POST. Here is my action:
export const createNewClient = (payload) =>
(dispatch, getState) => {
dispatch({ type: REQUEST_CREATE_NEW_CLIENT, payload })
const jwt = getJwt()
if (!jwt) {
throw new Error('No JWT present')
}
const token = jwt.access_token
const headers = new Headers({
'Authorization': `bearer ${token}`
})
debugger
const task = fetch('/api/client/create', {
method: 'POST',
body: JSON.stringify(payload),
headers,
})
.then(handleErrors)
.then(response => response.json())
.then(data => {
dispatch({ type: RECEIVE_CREATE_NEW_CLIENT, payload: data })
dispatch({
type: SAVE_MESSAGE, payload: {
message: "Successfully saved client",
type: 'success'
}
})
})
.catch(error => {
//clearJwt()
dispatch({ type: ERROR_CREATE_NEW_CLIENT, payload: error.message })
dispatch({ type: SAVE_MESSAGE, payload: { message: error.message, type: 'error' } })
})
addTask(task)
return task
}
I tried modifying the headers to include UTF-8 like so.
headers: {
'Content-Type': 'application/json;charset=UTF-8'
},
However this just gave me 401 Unauthorized which means that by using this it is the correct media type but now wont be accepted.
That same JWT works fine in a Fetch GET command so the JWT itself is not the problem - I believe it might be the way I am writing the "Fetch".
Now I do the same thing in Postman and I get through but not with this Fetch...
What have I missed or incorrectly structured for a Fetch POST so that JWT is accepted etc
If it works as in the provided image
then the following will work
fetch('/api/client/create', {
method: 'POST',
body: JSON.stringify(payload),
headers: {
'Authorization': `bearer ${token}`,
'Content-Type': 'application/json',
}
})

Categories

Resources