error 403 showing while fetching the flight data from API - javascript

There are the errors
Theses are the errors.
componentDidMount() {
const options = {
method: 'GET',
url: 'https://timetable-lookup.p.rapidapi.com/TimeTable/BOS/LAX/20191217/',
headers: {
'X-RapidAPI-Key': 'SIGN-UP-FOR-KEY',
'X-RapidAPI-Host': 'timetable-lookup.p.rapidapi.com'
}
};
axios.request(options).then(function (response) {
console.log(response.data);
}).catch(function (error) {
console.error(error);
});
}
i am trying to fetch data for a flight booking system and getting this error.

Related

Json cant go through webhook call on form submit

I have form submit function with axios:
const onSub mit = (data) => {
const webhookUrl = 'MY URL';
const info = JSON.stringify(data);
axios({
method: 'post',
url: `${webhookUrl}`,
data: info,
config: { headers: { 'Content-Type': 'application/json' } },
})
.then(function (response) {
alert('Message Sent!');
})
.catch(function (response) {
//handle error
console.log(response);
});
};
and here is what i get after JSON.stringify inside info:
{"fullname":"Temirlan","email":"test#mail.com","phone":"0179890808","proffesion":false,"message":"test"}
This is what i get in my webhook after form is submitted which is wrong:
However if i use Thunder client and post same data:
I get it correctly:
What am i doing wrong?
So I used different approach with axios and it worked:
let axiosConfig = {
headers: {
'Content-Type': 'application/json;charset=UTF-8',
'Access-Control-Allow-Origin': '*',
},
};
axios
.post(webhookUrl, info, axiosConfig)
.then((res) => {
console.log('RESPONSE RECEIVED: ', res);
})
.catch((err) => {
console.log('AXIOS ERROR: ', err);
});

React and NodeJS: How can i use received data from Server on Client?

I want to use received data from server on client . I use a NodeJS Server with NextJS and React.
I use this function on the server:
function addEmailToMailChimp(email, callback) {
var options = {
method: 'POST',
url: 'https://XXX.api.mailchimp.com/3.0/lists/XXX/members',
headers:
{
'Postman-Token': 'XXX',
'Cache-Control': 'no-cache',
Authorization: 'Basic XXX',
'Content-Type': 'application/json'
},
body: { email_address: email, status: 'subscribed' },
json: true
};
request(options, callback);
}
The function will be run from this point:
server.post('/', (req, res) => {
addEmailToMailChimp(req.body.email, (error, response, body) => {
// This is the callback function which is passed to `addEmailToMailChimp`
try {
var respObj = {}; //Initial response object
if (response.statusCode === 200) {
respObj = { success: `Subscribed using ${req.body.email}!`, message: JSON.parse(response.body) };
} else {
respObj = { error: `Error trying to subscribe ${req.body.email}. Please try again.`, message: JSON.parse(response.body) };
}
res.send(respObj);
} catch (err) {
var respErrorObj = { error: 'There was an error with your request', message: err.message };
res.send(respErrorObj);
}
});
})
The try method is used to verify that an email address could be successfully saved to MailChimp. An appropriate message is sent to the client.
On the Client-Side, i use this function to receive and display the data from the server:
handleSubmit() {
const email = this.state.email;
this.setState({email: ""});
fetch('/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({email:email}),
}).then(res => {
if(res.data.success) {
//If the response from MailChimp is good...
toaster.success('Subscribed!', res.data.success);
this.setState({ email: '' });
} else {
//Handle the bad MailChimp response...
toaster.warning('Unable to subscribe!', res.data.error);
}
}).catch(error => {
//This catch block returns an error if Node API returns an error
toaster.danger('Error. Please try again later.', error.message);
});
}
The problem: The email address is saved successfully at MailChimp, but the message is always displayed: 'Error. Please try again later.'from the .catch area. When i log the error from the catch area i get this:
TypeError: Cannot read property 'success' of undefined
Where is my mistake? I have little experience in Node.js environments. I would be very grateful if you could show me concrete solutions. Thank you for your replies.
With fetch theres no data property on the response. You have to call res.json() and return that promise. From there the response body will be read and deserialized.
handleSubmit() {
const email = this.state.email;
this.setState({email: ""});
fetch('/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({email:email}),
})
.then(res => {
console.log(res); //to make sure the expected object is returned
if(res.data.success) {
//If the response from MailChimp is good...
toaster.success('Subscribed!', res.data.success);
this.setState({ email: '' });
} else {
//Handle the bad MailChimp response...
toaster.warning('Unable to subscribe!', res.data.error);
}
}).catch(error => {
//This catch block returns an error if Node API returns an error
toaster.danger('Error. Please try again later.', error.message);
});
}
Two things you need to change:
Call and wait for res.json() to get the response body as json object.
The result of 1. is your 'data' object that you can use directly
handleSubmit() {
//...
fetch('/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({email:email}),
})
.then(res => res.json())
.then(data => {
if(data.success) {
//...
toaster.success('Subscribed!', data.success);
} else {
toaster.warning('Unable to subscribe!', data.error);
}
}).catch(error => {
//...
});
}

How to upload FormData using Axios?

I am trying to upload 3 photos from frontend using formData. It will call an external API to make the upload. But encountered some errors as below.
Frontend upload
const formData = new FormData()
formData.append('photoA', this.photoA)
formData.append('photoB', this.photoB)
formData.append('photoC', this.photoC)
axios.post(`http://localhost:4172/uploadDocs`,
{
data: formData,
accessToken: store.state.token
},
{ headers: {
// 'Content-Type': 'Application/json',
// 'x-access-token': localStorage.getItem('token')
}
}
).then (function (response) {
return response.data
})
Nodejs upload API
async uploadDocs (req, res) {
const options = {
method: "POST",
url: "https://example.com/api/v1/users/uploadDocuments?access_token=" + req.body.accessToken,
headers: {
//"Authorization": "Basic " + auth,
//"Content-Type": "multipart/form-data"
},
data: req.body.data
};
try {
request(options, function (err,response,body){
if (err) {
res.send(err)
} else {
res.send(response.body)
}
})
} catch (error) {
res.status(400).send({
error: "Server error."
})
}
}
So there are 2 errors here:
a) Frontend error: It keeps giving Cannot POST / error in html
b) Backend error:
<h1>Cannot read property 'photoA' of undefined</h1>
<h2></h2>
<pre></pre>
Been struggling with this for days. Any help will be very much appreciated.

React Js: Uncaught (in promise) SyntaxError: [duplicate]

This question already has answers here:
POST Request with Fetch API?
(7 answers)
Closed last month.
I am trying to do a POST request through fetch in reactjs. I went through some docs but my error not solved.Can anyone please help me out?
Here is my reactjs code:
handleSubmit(e) {
e.preventDefault();
var self = this;
const payload = {
id: 111,
studentName: 'param',
age: 24,
emailId: 2
};
fetch({
method: 'POST',
url: 'http://localhost:8083/students',
body: payload,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})
.then(function(response) {
return response.json()
}).then(function(body) {
console.log(body);
});
}
}
If any one familiar with reactjs, just give a simple example how to call post request.Either by using fetch or axios.
Here is an example..
fetch('http://myAPiURL.io/login',{
method:'POST',
headers:{
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body:JSON.stringify({
email: userName,
password: password
})
}).then(function (response) {
//Check if response is 200(OK)
if(response.ok) {
alert("welcome ");
}
//if not throw an error to be handled in catch block
throw new Error(response);
})
.catch(function (error) {
//Handle error
console.log(error);
});
for more info on how to use `fetch` https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
Well I answered a similar question just now. here.
Well the great thing about React is that it's just Javascript.
So all you need is something to do a POST do your server!
You can use the native fetch function or a full-on library like axios
Examples using both could be:
// Using ES7 async/await
const post_data = { firstname: 'blabla', etc....};
const res = await fetch('localhost:3000/post_url', { method: 'POST', body: post_data });
const json = await res.json();
// Using normal promises
const post_data = { firstname: 'blabla', etc....};
fetch('localhost:3000/post_url', { method: 'POST', body: post_data })
.then(function (res) { return res.json(); })
.then(function (json) { console.log(json); };
// AXIOS example straight from their Github
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});

Axios http request in Firebase App - 400 Bad Request

I use axios version 0.13.1 and if I want to get data with orderBy and limitToFirst parameters, I got 400 Bad request error.
With this http request I get 400 error:
axios({
method: 'get',
url: 'https://tracker-ag.firebaseio.com/groups.json',
params: {
auth: AccessStore.getToken(),
orderBy: "$key",
limitToFirst: 2,
}
}).then(function (response) {
responseHandler(USERS_GET, '', response.data);
})
.catch(function (error) {
console.log("Error during fetching data " + error.message);
});
This http request without orderBy and limitToFirst parameters works:
axios({
method: 'get',
url: 'https://tracker-ag.firebaseio.com/groups.json',
params: {
auth: AccessStore.getToken(),
}
}).then(function (response) {
responseHandler(USERS_GET, '', response.data);
})
.catch(function (error) {
console.log("Error during fetching data " + error.message);
});

Categories