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
Related
I can sign up a user via postman. But when I use my app I am getting that error. My signup method is ok. But my fetch address is not good. here is method.
export const signup = user => {
return fetch(`${API}/signup`, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(user)
})
.then(response => {
return response.json();
})
.catch(err => {
console.log(err);
});
};
const API = process.env.REACT_APP_API_URL;
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.
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)
})
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));
}
I am using react native to create an application to act as a website that currently exists (with a user interface that works on a phone). i am using the "fetch" method to send a Http POST request to get information from a web server. The web server sends a response but it doesn't include the response message:
I apologies that is an image but the debugger is not working for me.
The code used to send the request:
HttpRequest = (RequestURL, callback) => {
var AdminLoginBindingModel = {
usr: this.state.username,
pwd: this.state.password,
}
fetch(RequestURL,
{
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(AdminLoginBindingModel)
})
.then((res) => {
callback(res);
})
.catch((error) => {
this.setState({Response: "Error: " + error});
})
}
The callback function in the parameters is just a function to change the state variable to display the information on the screen
ValidateResponse(response){
this.setState({Response: "Result: " + JSON.stringify(response),
displayMessage: "Success"});
console.log(JSON.stringify(response));
}
The Request being sent is "https://mibase-test.mibase.com.au/members/api/startSession.php?usr=&pwd="
The server responds with a json object regardless of a correct login or not
Edit:
Changing the response to
.then((res) => {
callback(res.json());
})
Result:
To get object from fetch response, you have to call res.json like following:
fetch(RequestURL, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(AdminLoginBindingModel)
})
.then(res => res.json()) // HERE
.then(obj => callback(obj))
But it occurs an error because response body itself is invalid json format. It contains some HTML tags:
{"member": {"username":"","password":"","key":"***","status":"No"}}<br><br>Username: <br>Key: ***
Please check the inplementation of server.
EDIT: full code here
const fetch = require("node-fetch")
HttpRequest = (RequestURL, callback) => {
const AdminLoginBindingModel = { usr: "foo", pwd: "bar" }
fetch(RequestURL, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(AdminLoginBindingModel)
})
.then(res => res.json())
.then(obj => callback(obj))
.catch(error => console.log(error))
}
const ValidateResponse = response => console.log(JSON.stringify(response))
URL = 'https://mibase-test.mibase.com.au/members/api/startSession.php?usr=&pwd='
HttpRequest(URL, ValidateResponse)
response doesn't contain received data directly. It provides interface methods to retrieve it. For example use response.json() to parse response text as JSON. It will return promise that resolves to the parsed object. You won't need to call JSON.parse on it:
fetch(RequestURL,
{
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(AdminLoginBindingModel)
})
.then((res) => {
return res.json();
}).then((obj) => {
console.log(obj);
});
Check https://developer.mozilla.org/en-US/docs/Web/API/Response and https://facebook.github.io/react-native/docs/network.html for more information.