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: ''}
]
Related
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
I am creating a DHL API for checking shipment rates. I have uploaded my Node.js Server using putty and it is running correctly when I enter my IP address and port number.
In development, there are no erros or issues and I get back the response and get the rates back from the form I have set up for my users.
but in Production, when I upload my website to Hostinger I get this error " Failed to load resource: net::ERR_SSL_PROTOCOL_ERROR"
In production, it sends my post request with HTTPS instead of HTTP. And even when I change the HTTPS to HTTP in the browser I get another error saying "Cannot GET /api/dhl"
Here are some images to help make it more clear:
The Errors.
When my website submits the post request with HTTPS instead of HTTP.
When I manually change the URL from HTTPS to HTTP
What am I doing wrong? Why is this happening and how can I fix it?
Here is my code:
const express = require('express');
const port = 3001
app.post('/api/dhl', (req, res) => {
const accountNum = req.body.accountNum
const fromCountriesCode = req.body.fromCountriesCode
const fromCountriesCapital = req.body.fromCountriesCapital
const fromCity = req.body.fromCity
const fromPostalCode = req.body.fromPostalCode
const toCountriesCode = req.body.toCountriesCode
const toCountriesCapital = req.body.toCountriesCapital
const toCity = req.body.toCity
const toPostalCode = req.body.toPostalCode
const weight = parseInt(req.body.weight)
const plannedShippingDate = req.body.date
const len = "5"
const width = "5"
const height = "5"
const isCustomsDeclarable = 'false'
const unitOfMeasurement = 'metric'
console.log(weight)
console.log(fromCountriesCode)
console.log(toCountriesCode)
console.log(fromCity)
console.log(toCity)
var options = { method: 'POST',
url: 'https://express.api.dhl.com/mydhlapi/rates',
headers:
{ 'postman-token': '',
'cache-control': 'no-cache',
authorization: 'Basic myauthkey',
'content-type': 'application/json' },
body:
{ customerDetails:
{ shipperDetails:
{ postalCode: fromPostalCode,
cityName: fromCity,
countryCode: fromCountriesCode,
addressLine1: '0' },
receiverDetails:
{ postalCode: toPostalCode,
cityName: toCity,
addressLine1: '0',
countryCode: toCountriesCode }
},
accounts: [ { typeCode: 'shipper', number: 'my account number' } ],
plannedShippingDateAndTime: '2021-08-25T13:00:00GMT+00:00',//Might need to change later
unitOfMeasurement: 'metric',
isCustomsDeclarable: true,
monetaryAmount: [ { typeCode: 'declaredValue', value: 10, currency: 'BHD' } ],
requestAllValueAddedServices: false,
returnStandardProductsOnly: false,
nextBusinessDay: false,
packages: [ { weight: weight, dimensions: { length: 5, width: 5, height: 5 } } ] },
json: true };
request(options, function (error, response, body) {
if (error) throw new Error(error);
res.send(body)
console.log(body);
});
});
//Start the Server
app.listen(port, () => {
console.log(`Server running at :${port}/`);
});
My Check-Rates File:
const getRateEstimate = () => {
axios.post('http://MY_IP:3001/api/dhl', {
fromCity,
fromCountriesCapital,
fromCountriesCode,
fromPostalCode,
toCountriesCapital,
toCountriesCode,
toPostalCode,
toCity,
weight,
}).then(response => {
console.log(response)
setData(response.data);
}).catch(e => {
console.log(e)
});
}
I have problem with sending data via POST method in fetch(). So the problem is that from this >> body: JSON.stringify({ id: uuid(), name, password }) it sends couple of times almost the same data (i receive unique id, and diplicated name and password). In the othet words: with one form submission, I've got few objects with differnt id, and same name and password. Code:
const handleSubmit = e => {
e.preventDefault();
users.map(user =>
user.name !== name && name.length >= 3 && password.length >= 5
? fetch('http://localhost:3003/users', {
method: 'POST',
body: JSON.stringify({ id: uuid(), name, password }),
headers: {
'Content-Type': 'application/json'
}
})
.then(res => {
if (res.ok) {
return res.json();
}
throw new Error('Error');
})
.then(c => setUser([...users, c]))
.then(errorUserChange(false))
: errorUserChange(true)
);
};
db.json:
{
"users": [
{
"id": "c1a10ab0-24c7-11ea-af77-3b28fe4ea407",
"name": "cccccc",
"password": "cccccc"
},
{
"id": "cbf73890-24c7-11ea-af77-3b28fe4ea407",
"name": "kkkkkkk",
"password": "kkkkk"
},
{
"id": "cbf786b0-24c7-11ea-af77-3b28fe4ea407",
"name": "kkkkkkk",
"password": "kkkkk"
}
]
}
Of course I know that's not the best way to hold password, I'm just practicing json server and fetch().
Thanks for any help!
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.
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 }
}) ...