passing parameters in post request axios - javascript

i have an object that i will use in post request using axios
employee:{
name: 'test',
email: 'test#gmail.com',
password: '123456',
role: {
created_at:"2018-08-03 07:34:30"
deleted_at:null
id:2
role_name:"employee"
updated_at:"2018-08-03 07:34:30"
}
},
this is my post request
axios.post('api/employees', vm.employee)
.then( response => {
alert("Employee Inserted");
vm.errors.clear();
vm.setFalse();
vm.fetchEmployees();
})
.catch( error => {
vm.errors.record(error.response.data);
});
how can I pass in post request only the role_name in role object together with name, email and password

If you mean headers by parameters then you can try:
var options = {
headers: {'X-My-Custom-Header': 'Header-Value'}
};
axios.post('api/employees', vm.employee, options);
Other wise just create a a body like this:
var options = {
headers: {'X-My-Custom-Header': 'Header-Value'}
};
axios.post('api/employees', {
name: vm.employee.name,
role: {
role_name: vm.employee.role.role_name
}
}, options);

I think this work for you.
axios.post('api/employees', {name: employee.name, email: employee.email, role_name: employee.role.role_name})
.then( response => {
alert("Employee Inserted");
vm.errors.clear();
vm.setFalse();
vm.fetchEmployees();
})
.catch( error => {
vm.errors.record(error.response.data);
});

If ES2015 is ok then this would be a shorter way to pass the data:
axios.post('api/employees', {
...employee,
role: { role_name: employee.role.role_name }
}) ...

Related

VUE application Response data useing Axios

I'm developing a VUE application, and I am trying to figure out how to handle post responses in Axios. I wrote it and used vue-router to make the fetch but decided to try out Axios.
Axious code:
methods: {
sendForm () {
console.log("submitHandler called - success!");
const payload = {
first_name: this.event.firstName,
last_name: this.event.lastName,
email: this.event.email,
password: this.event.password,
name: this.event.agencyName,
abbreviation: this.event.abbreviation,
type: this.event.agencyType,
address: this.event.agencyAddress,
city: this.event.agencyCity,
state: this.event.state,
zipcode: this.event.zipcode,
phone: this.event.phone,
}
axios.post(process.env.VUE_APP_API_URL+"/agency/add",payload)
.then(function (response) {
console.log('Response', response)
//reformat returned expiration date for displaying on webpage
console.log("Expiry date:", response.data.data.agency.expiry);
let expd = dayjs(response.data.data.agency.expiry).format("dddd, MMMM D YYYY");
//Write retunred values to storeage
store.user = {
id: response.data.data.user.id,
first_name: response.data.data.user.first_name,
last_name: response.data.data.user.last_name,
email: response.data.data.user.email,
agency_name: response.data.data.agency.name,
expiry_date: expd,
}
router.push("/SignUpConfirm");
})
.catch(function (error) {
console.log('Error', error.message);
Swal.fire({
icon: 'error',
title: 'Oops...',
text: error.message,
})
})
}
}
My issue/question is, for some reason, I have to use "response.data.data.foo" to drill to the response I want.
When I used the built-in view router, I just used "data.foo"
Vue-router option:
methods: {
submitHandler() {
console.log("submitHandler called - success!");
const payload = {
first_name: this.firstName,
last_name: this.lastName,
email: this.email,
password: this.password,
agency_name: this.agencyName,
abbreviation: this.abbreviation,
agency_type: this.agencyType,
agency_address: this.agencyAddress,
agency_city: this.agencyCity,
state: this.state,
zipcode: this.zipcode,
phone: this.phone,
}
const requestOptions = {
method: "POST",
body: JSON.stringify(payload),
}
fetch(process.env.VUE_APP_API_URL+"/agency/add", requestOptions)
.then((response) => response.json())
.then((response) => {
if (response.error) {
console.log("Error:", response.message);
Swal.fire({
icon: 'error',
title: 'Oops...',
text: response.message,
})
} else {
//reformat returned expiration date for displaying on webpage
console.log("Expiry date:", response.data.agency.expiry);
let expd = dayjs(response.data.agency.expiry).format("dddd, MMMM D YYYY");
//Write retunred values to storeage
store.user = {
id: response.data.user.id,
first_name: response.data.user.first_name,
last_name: response.data.user.last_name,
email: response.data.user.email,
agency_name: response.data.agency.name,
expiry_date: expd,
}
router.push("/SignUpConfirm");
}
})
}
}
Your API response is probably something like this (after parsing JSON of course)
{
data: {
user: {
......
}
}
}
For clarity, lets say it is instead returning
{
topLevel: {
nextLevel: {
......
}
}
}
so, below, toplevel would actually be data, and nextLevel would actually be user ... but, using these abstract names of toplevel and nextLevel should help illustrate why you end up with data.data in axios
axios response schema is as follows
{
data: {}, // server response
status: 200, // response status
statusText: 'OK', // response status text
headers: {}, // response headers
// etc - there's more but not relevant
}
So in
axios.post(....)
.then(function (response) {
})
then nextLevel is clearly response.data.topLevel.nextlevel
Note that the response from the server here is a property of the data property of the response variable - i.e. two "levels" inside the response variable
When using fetch
fetch(....)
.then(response => response.json())
.then(response => .....)
(it doesn't help clarity that you use response in both .then by the way, I'd use result in the second .then)
in the above, the FIRST response is
{
status: 200, // response status
statusText: 'OK', // response status text
headers: {}, // response headers
body: // a readableStream of the response body
json() {}, // method to parse the body as json
// .... etc
}
and the second response is the parsed JSON response from your server,
so in this case nextLevel is response.topLevel.nextLevel
And the response from the server here is a property of (the second) response variable

How I can Update only relevant data with this Update Controller?

Update Controller
exports.UpdatePanelMembers = (req, res) => {
const { panelId } = req.params;
if (panelId) {
Panel.findOneAndUpdate(
{ _id: panelId },
{
panelMembers: {
member1: {
memberId: req.body.panelMembers.member1.memberId,
fullName: req.body.panelMembers.member1.fullName,
username: req.body.panelMembers.member1.username,
},
member2: {
memberId: req.body.panelMembers.member2.memberId,
fullName: req.body.panelMembers.member2.fullName,
username: req.body.panelMembers.member2.username,
},
member3: {
memberId: req.body.panelMembers.member3.memberId,
fullName: req.body.panelMembers.member3.fullName,
username: req.body.panelMembers.member3.username,
},
},
}
).exec((error, result) => {
if (error) return res.status(400).json({ error });
if (result) {
res.status(202).json({ result });
}
});
}
};
In this code, if I update member1 details only, other data will be erased. So I want to update only relevant data like this postman JSON.
Postman JSON Code
{
"panelMembers": {
"member1": {
"username":"john.j",
"fullName":"John Jade",
"memberId":"member123"
}
}
}
Postman
Frontend is like this
You just have to update member1 in panelMembers object. So for that, send member1 object in request from postman and make your query as :-
Panel.findOneAndUpdate({ _id: panelId },{'panelMembers.$.member1': member1})
This will only update member1 object. Other objects will not be affected or erased.

Chaining an axios.get call to use the response for an axios.all multiple request

I'm having difficulties to understand how Shall I handle this type of calls. I need an initial axios.get call and loop through to make an axios.all call. This is my code:
export async function getServerSideProps(context) {
const axios = require("axios");
const options = {
method: 'GET',
url: 'xxxxx',
params: { id_user: 'xxxxx' },
headers: {
'X-RapidAPI-Host': 'xxxxxxx',
'X-RapidAPI-Key': 'xxxxxxx'
}
};
const res = axios.request(options).then(function (response) {
axios.all(response.data.users.map(user => {
axios.get('xxxxxxx', {
params: { response_type: 'short', ig: user.username, corsEnabled: 'true' },
headers: {
'X-RapidAPI-Host': 'xxxxx',
'X-RapidAPI-Key': 'xxxxxxx'
}
})
})).then(res => {
return res.data
})
})
const payload = await res;
I have an error on the page when I try to console log the payload. What's going worng with my call?
Looks like you need a return inside your map.
The below code worked for me and the unique params were updated on each request. Once you prepare your series of endpoints or whatever is unique for each request (user data per your sample code) you map over the relevant data and make all your get requests. The result returned will be an array of the responses you get back from each request once all of the requests have finished.
Regarding chaining together requests, you can use any number of .then() to kick off other actions. You mention needing an id from an initial get request, so here is a solution based on that example.
Hope you find it helpful.
const users = [{ username: '1' }, { username: '2' }, { username: '3' }];
axios
.get('https://jsonplaceholder.typicode.com/posts')
.then((res) => {
console.log(res);
// simulating getting some id you need...
const id = res.data[4].id;
console.log(id);
return id;
})
.then((id) => {
axios
.all(
users.map((user) => {
return axios.get('https://jsonplaceholder.typicode.com/posts', {
params: {
response_type: 'short',
// just an example of using id...
importantId: id,
ig: user.username,
corsEnabled: 'true',
},
headers: {
'X-RapidAPI-Host': 'xxxxxxx',
'X-RapidAPI-Key': 'xxxxxxx',
},
});
})
)
.then((res) => {
console.log(res);
});
});

How to extract data from an array of objects to render a list in an html email template? Using React/Formik/Sendgrid

So, basically I have a form data that I am having trouble parsing correctly. I keep getting [object Object]'s in the response for the listPets variable. Every other variable is mapping correctly. Anyone have any ideas on how I could go about this? :)
<Formik
initialValues={{
email: '',
password: '',
jobType: '',
comments: '',
cookies: [],
terms: '',
newsletter: '',
firstName: '',
pets: [{ type: '', name: '', id: '1' }]
}}
validationSchema={ LoginSchema }
onSubmit={
async data => {
await sleep(1000);
setStatus(prevStatus => ({ ...prevStatus }));
const res = await fetch('/api/send', { method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
});
const text = await res.text();
handleResponse(res.status, text);
}
}
>
const sgMail = require('#sendgrid/mail');
export default async function(req, res){
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
const { email, comments, firstName, cookies, jobType, pets } = req.body;
const content = {
to: '',
from: email,
subject: `New Message From - ${email}`,
text: comments,
html: `
<p>Hi, ${firstName}.</p>
<p>${comments}</p>
<p>${cookies}</p>
<p>${jobType}</p>
<p>${listPets}</p>
`
};
try {
console.log('Content', content);
res.status(200).send('Message sent successfully.');
} catch (error) {
console.log('ERROR', error);
res.status(400).send('Message not sent.');
}
}
Why not use JSON.stringify(pets) to debug whats happening? I would have commented but i dont have enough reputation.

Send auto post request in react without a form?

Normally you send a post request via a submit button on a form. However I need to send a post request without a form. In fact, I need to send post request as soon as the user has selected location & status for a patient.
I tried posting handleAutoObsSubmit() on componentDidUpdate() however this post request is sent every time there is a DOM update i.e. click on other button, I only want it to send once.
Is it even a thing to send post request like this?
handleAutoObsSubmit = () => {
const postObsUrl = '/observation/record';
this.state.patientInfo.forEach(patient => {
if (patient.locationInfo !== '' && patient.status !=='') {
const data = {
room: patient.room,
patient: patient.name,
location: patient.locationInfo,
status: patient.status,
};
fetch(postObsUrl, {
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json'
}
})
.then((res) => {
console.log(data);
if (!res.ok) {
console.log('request failed');
} else {
console.log('request sent');
}
});
}
});
}
patientInfo = [
{ count: 959999, room: "1", name: 'John Nero', locationInfo: '', status: ''},
{ count: 959999, room: "2", name: 'Shawn Michael', locationInfo: '', status: ''},
{ count: 959999, room: "3", name: 'Gereth Macneil', locationInfo: '', status: ''}
]

Categories

Resources