Call REST API with auth token with React.js - javascript

This is a try of call a REST API that as an authentication token with React.js. I'm sending the token request as POST and it's been read as GET, can someone help me please?
componentDidMount() {
fetch("theURL/api-token-auth/", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
email: "EMAIL",
password: "PASSWORD"
}
})
.then(res => {
if (res.ok) {
return res.json();
} else {
throw Error(res.statusText);
}
})
.then(json => {
this.setState({
isLoaded: true,
token: json
});
})
.catch(error => console.error(error));
}

You are correctly using the method POST, so that's not an issue. However, the data you want to send should be in the body instead of in the headers.
componentDidMount() {
const email = "test#example.com";
const password = "foobar";
fetch("theURL/api-token-auth/", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({
email,
password
})
})
.then(res => {
if (res.ok) {
return res.json();
} else {
throw Error(res.statusText);
}
})
.then(json => {
this.setState({
isLoaded: true,
token: json
});
})
.catch(error => console.error(error));
}

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));

Axios can't send credentials

I'm trying to include credentials to my requests
I'm using axios but axios don't send credentials with request.
This is how i do it with axios.
const axiosConfig = {
withCredentials: true,
headers: {
Accept: "application/json",
"Content-Type": "application/json"
}
};
axios
.get("someurl" + data, axiosConfig)
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error);
});
But when i try it with fetch everything work.
fetch("someurl" + data, {
credentials: "include"
})
.then(function(response) {
return response.json();
})
.then(result => {
console.log(result);
});
how make it work with axios too?
You should see the auth parameter inside the axios config object
auth: {
username: 'janedoe',
password: 's00pers3cret'
}
see https://github.com/axios/axios

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

axios post method 400 bad request

I'm getting a JSON file, editing it and trying send it back to server. But when I use post method it throws an error 400 bad request.In response shows "no template_id or no template_json presented". What could be the problem?
saveData() {
const { data } = this.state
let token = localStorage.getItem("token")
axios
.post(
"http://dev.candidates.hrmessenger.com/stage/set-template",
data,
{
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
},
)
.then(res => {
console.log(res)
})
.catch(error => {
console.log(error)
})
}
Please try to use this:
data.template_id = 1;
saveData() {
const { data } = this.state
data.template_id = 1;
let token = localStorage.getItem("token")
axios
.post(
"http://dev.candidates.hrmessenger.com/stage/set-template",
data,
{
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
},
)
.then(res => {
console.log(res)
})
.catch(error => {
console.log(error)
})
}
You missed the parameter template_id, or you need to ask from your API developer to send the documentations of the POST Method API.

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)
})

Categories

Resources