let's say I have a service that is sending a post request to my API, and as soon as the response has arrived, I'd like a custom function to be executed as part of the process.
public signin(){
return this.http.post<any>(`${env.API_URL}/user/signin`, { username: user.username, password: user.password }).toPromise();
}
I have tried using the pipe operator, but for some reason it wasn't sending errors to the returned promise.
public signin(){
return this.http.post<any>(`${env.API_URL}/user/signin`, { username: user.username, password: user.password }).pipe(
tap(
data => this.customFunction(data),
error => error
)
).toPromise();
}
One option is to use code like this:
getMovies(): Observable<IMovie[]> {
return this.http.get<IMovie[]>(this.moviesUrl).pipe(
tap(data => console.log(JSON.stringify(data))),
catchError(this.handleError)
);
}
You could then add your custom function in the tap.
So your code would look more like this:
public signin() {
return this.http.post<any>(`${env.API_URL}/user/signin`, { username: user.username, password: user.password }).pipe(
tap(data => this.customFunction(data)),
catchError(error => console.log(error))
);
}
You can do this using the following code:
public signin() {
return this.http.post<any>(`${env.API_URL}/user/signin`, { username: user.username, password: user.password })
.toPromise()
.then((data) => {
this.customFunction(data)
})
.catch(this.handleError);
}
Then just define a handle error function, or use a lambda function just like with data if you prefer
Related
I'm trying to send GET request as second parameter but it doesn't work while it does as url.
This works, $_GET['naam'] returns test:
export function saveScore(naam, score) {
return function (dispatch) {
axios.get('http://****.nl/****/gebruikerOpslaan.php?naam=test')
.then((response) => {
dispatch({type: "SAVE_SCORE_SUCCESS", payload: response.data})
})
.catch((err) => {
dispatch({type: "SAVE_SCORE_FAILURE", payload: err})
})
}
};
But when I try this, there is nothing in $_GET at all:
export function saveScore(naam, score) {
return function (dispatch) {
axios.get('http://****.nl/****/gebruikerOpslaan.php',
{
password: 'pass',
naam: naam,
score: score
})
.then((response) => {
dispatch({type: "SAVE_SCORE_SUCCESS", payload: response.data})
})
.catch((err) => {
dispatch({type: "SAVE_SCORE_FAILURE", payload: err})
})
}
};
Why can't I do that? In the docs it clearly says it's possible. With $_POST it doesn't work either.
axios.get accepts a request config as the second parameter (not query string params).
You can use the params config option to set query string params as follows:
axios.get('/api', {
params: {
foo: 'bar'
}
});
On client:
axios.get('/api', {
params: {
foo: 'bar',
},
});
On server:
function get(req, res, next) {
let param = req.query.foo
// ...
}
For me I was trying to send params using axios.post.
When switch both client and server to axios.get, req.query.foo worked like a charm
This works fine for me. When it is post request nested data object isn't needed but in get requests, in order to send data, you need it.
axios.get('/api', {
data: {
foo: 'bar'
}
}
Hello my fellow nerds,
I am running into an issue where when I make a POST request (using Axios library inside of React function), it automatically appends all of the data from the "Create a User" form into search parameters in the URL of the page upon submission. I don't like this because I'd rather this stay hidden within the POST request, not flung out onto the page URL.
Image: URL after user was created
This is a direct result of React Router adding the data sent in the request of the body being appended to the location.search of react router's history object. So, naturally, since the react router history object is mutable, I tried adding this to the response of the submission:
this.props.location.search.replace({*some random parameter stuff here*});
This was in hopes it would remove all of that stuff from the URL and redirect to the page without search parameters. Anyways, I have seen a few other posts similar in nature but they don't seem to answer this exact question.
TL;DR: I am trying to send a POST request without React Router adding my req.body data to the params in my URL and the location.search object.
MY CODE:
Users.js: (front end)
handleSubmit (e) {
Axios.post(`${server}/s/admin/users/create`, {
headers: {
'Content-Type': 'application/json'
},
data: {
firstName: this.state.firstName,
lastName: this.state.lastName,
username: this.state.username,
password: this.state.password,
email: this.state.email
}
}).then((res) => {
console.log(res);
}).catch(err => console.log(err));
}
users.js: (back end)
app.post("/s/admin/users/create", (req, res) => {
let rb = req.body.data;
let newUser = new User({
_id: uid.time(),
orgID: req.session.orgID,
email: rb.email,
username: rb.username,
password: bcrypt.hashSync(rb.password, hashRate),
firstName: rb.firstName,
lastName: rb.lastName,
data: { exist: "true" },
settings: { exist: "true" }
});
// Save new owner to db
newUser.save((err, data) => {
if (err) return console.error(err);
res.json({info: `A new user, ${newUser.firstName} ${newUser.lastName}, has been created successfully.`});
});
});
Thank you!
P.S. This is my first post, thank you for your patience. I've tried searching and solving this issue for about a day now.
Can you try rewriting it this way? cause axios.post expect
axios({
method: 'post',
url: `${server}/s/admin/users/create`,
headers: {
'Content-Type': 'application/json'
},
data: {
firstName: this.state.firstName,
lastName: this.state.lastName,
username: this.state.username,
password: this.state.password,
email: this.state.email
}
}).then((res) => {
console.log(res);
}).catch(err => console.log(err));
Axios.post method expect the second argument as data but you have passed config, another way is to pass data and config in the third argument.
handleSubmit(e) {
Axios.post(`${server}/s/admin/users/create`, {
firstName: this.state.firstName,
lastName: this.state.lastName,
username: this.state.username,
password: this.state.password,
email: this.state.email
}, {
headers: {
'Content-Type': 'application/json'
}
}
}).then((res) => {
console.log(res);
}).catch(err => console.log(err));
}
I am trying to use Axios post to create a user in my Django Rest Framework api.
Currently getting "Request failed with status code 400" when trying to post.
It works perfectly fine in postman.
drfServer.js
import axios from 'axios';
export default axios.create({
baseURL: 'https://example.com'
});
AuthContext.js
const signup = (dispatch) => async ({ email, password }) => {
try {
const response = await drfApi.post('/user/',
{
data: {
username: email,
password: password
}
}
);
// await AsyncStorage.setItem('token', response.data.token);
// dispatch({ type: 'signin', payload: response.data.token });
// navigate('Task')
} catch (err) {
console.log(err.message)
dispatch({ type: 'add_error', payload: 'Something went wrong with sign up' })
}
};
I tried using fetch and it works. But with Axios I am not getting it right.
Any ideas how to make it work?
Can you try this code.
const signup = ({email,password}) => dispatch => {
return axios({
method: "post",
url: "your api url",
data: {
username: email,
password
})
.then(result => {
console.log(result.data);
})
.catch(error => {
console.log(error);
})
};
You can find the axios example code here https://github.com/axios/axios
Maybe you can try this :
const response = await drfApi.post('/user/', {
username: email,
password: password
}
);
As using axios.post will automatically take the 2nd param and make it an object with data key
I am running a react app with nodejs acting as an api to connect to my database.
For my log in I am sending data to the server, and it is returning a pass or fail.
However I am not sure how to extract this json object.
I have looked at the request and response, and as I have manipulated the json object the response content-length has been changing so I believe it must be there somewhere.
SERVER CODE:
app.post('/api/checkLogin', async (req,res) => {
console.log(req.body);
const {username, password} = req.body;
try{
let state = await DB.checkPassword(username, password);
console.log(state);
if(!state){
res.status(401).json({
error: 'Incorrect username or password',
yay: 'idk work?'
});
}
else if(state){
res.status(200).json({
message: 'we in boys'
});
} else {
res.status(6969).json({
err: 'idk mane'
});
}
} catch(e) {
console.log(e);
}
})
CLIENT CODE:
onSubmit = (event) => {
event.preventDefault();
fetch('/api/checkLogin', {
method:'POST',
body: JSON.stringify({username: this.state.username, password: md5(this.state.password)}),
headers: {
'Content-Type':'application/json'
}
}).then(res => {
if(res.status ===200) {
this.props.loggedIn();
} else if(res.status ===401){
console.log(res.status);
alert('wrong username or password');
}else{
const error = new Error(res.error);
throw error;
}
}).catch(err => {
console.log(err);
alert(err);
});
}
What I was sort of expecting as a way to extract the data would be.
On the server:
res.status(200).json({ message : 'mssg'});
On the client:
console.log(res.status.message) // 'mssg'
Thanks Jin and this post I found for the help Fetch API get raw value from Response
I have found that both
res.status(xxx).json({ msg: 'mssg'}) and res.status(xxx).send({msg: 'mssg'}) work.
The json, or sent message can then be interpreted on the client side with a nested promise. This is done with...
fetch('xxx',headers n stuff).then(res => {
res.json().then((data) => {console.log(data.message)});
//'mssg'
res.text().then((data) => { let data1 = JSON.parse(data); console.log(data1.message);});
//'mssg'
});
According to my experience, using res.status(200).send({message: 'mssg'}) is better.
And you can get data after calling api by using res.data.
Then you can get result as below:
{
message: 'mssg'
}
Here is something that may help.
onSubmit = (event) => {
event.preventDefault();
const userData = {
username: this.state.username, // I like to store in object before passing in
password: md5(this.state.password)
}
fetch('/api/checkLogin', {
method:'POST',
body: JSON.stringify(userData), //stringify object
headers: {
'Content-Type':'application/json'
}
}).then(res => res.json()) // convert response
.then(responseData => {
let status = responseData.whatObjectWasPassedFromBackEnd;
status === 200 ? do something on pass: do something on fail
})
.catch(err => {
console.log(err);
alert(err);
});
}
I am trying to post on an API with some query params.
This is working on PostMan / Insomnia when I am trying to by passing mail and firstname as query parameters :
http://localhost:8000/api/mails/users/sendVerificationMail?mail=lol%40lol.com&firstname=myFirstName
However, when I am trying to do it with my react native app, I got a 400 error (Invalid Query Parameters).
This is the post method :
.post(`/mails/users/sendVerificationMail`, {
mail,
firstname
})
.then(response => response.status)
.catch(err => console.warn(err));
(my mail and firstname are console.logged as follow: lol#lol.com and myFirstName).
So I don't know how to pass Query Parameters with Axios in my request (because right now, it's passing data: { mail: "lol#lol.com", firstname: "myFirstName" }.
axios signature for post is axios.post(url[, data[, config]]). So you want to send params object within the third argument:
.post(`/mails/users/sendVerificationMail`, null, { params: {
mail,
firstname
}})
.then(response => response.status)
.catch(err => console.warn(err));
This will POST an empty body with the two query params:
POST
http://localhost:8000/api/mails/users/sendVerificationMail?mail=lol%40lol.com&firstname=myFirstName
As of 2021 insted of null i had to add {} in order to make it work!
axios.post(
url,
{},
{
params: {
key,
checksum
}
}
)
.then(response => {
return success(response);
})
.catch(error => {
return fail(error);
});
In my case, the API responded with a CORS error. I instead formatted the query parameters into query string. It successfully posted data and also avoided the CORS issue.
var data = {};
const params = new URLSearchParams({
contact: this.ContactPerson,
phoneNumber: this.PhoneNumber,
email: this.Email
}).toString();
const url =
"https://test.com/api/UpdateProfile?" +
params;
axios
.post(url, data, {
headers: {
aaid: this.ID,
token: this.Token
}
})
.then(res => {
this.Info = JSON.parse(res.data);
})
.catch(err => {
console.log(err);
});
You can use params and body together in a request with axios
sendAllData (data) {
return axios
.post(API_URL + "receiveData", JSON.stringify(data), {
headers: { "Content-Type": "application/json; charset=UTF-8" },
params: { mail: xyx#example.col }, //Add mail as a param
})
.then((response) => console.log("repsonse", response.status));
}