fetch API with POST method giving me 500 (Internal Server Error) - post

I'm using a fetch with POST method to get data from an API in my index.html page but am getting 500 status code, can somebody please guide me on what could be wrong in my code
<body>
<h1>Flights Finder</h1>
<script type="text/javascript">
fetch("https://skyscanner-skyscanner-flight-search-v1.p.rapidapi.com/apiservices/pricing/v1.0", {
'method': 'POST',
'headers': {
'x-rapidapi-host': 'skyscanner-skyscanner-flight-search-v1.p.rapidapi.com',
'x-rapidapi-key': 'API_KEY',
'content-type': 'application/x-www-form-urlencoded'
},
'body': {
'inboundDate': '2019-11-24',
'cabinClass': 'business',
'children': '0',
'infants': '0',
'country': 'US',
'currency': 'USD',
'locale': 'en-US',
'originPlace': 'SFO-sky',
'destinationPlace': 'LHR-sky',
'outboundDate': '2019-11-16',
'adults': '1'
}
})
.then(response => {
console.log(response);
})
.catch(err => {
console.log(err);
});
</script>
</body>

Error code 500 is an internal server error. You should check if no error is being thrown on the server.

Related

Error: Request is too large when Uploading Youtube Video via API

I'm getting an error when trying to upload a Youtube video (3MB only) via a POST request saying that the request is too large. What am I missing?
axios({
method: 'POST',
url: 'https://www.googleapis.com/upload/youtube/v3/videos',
headers: {
'Accept': 'application/json',
'Content-Type': 'video/*',
'Authorization': `Bearer <my_access_token>`
},
params: {
'uploadType': 'resumable',
'key': <my_api_key>,
'part': 'snippet,status',
'snippet': {
'title': 'Test Upload 1',
'description': 'Test Description 1',
'tags': ['tag1', 'tag2'],
'defaultLanguage': "en_US",
'categoryId': '24'
},
'status': {
'privacyStatus': "private"
},
},
data: fs.createReadStream(`${process.cwd()}/video.mp4`),
})
.then( res => console.log(res))
.catch(console.error);

Cannot consume rest api (Web Api) from component React

I'm developing a web, it consume a rest api, this api rest is build in asp.net as a Web Api. My issue is present when try consume an endpoint, because use fetch, but this not show any.
this is my code
import React from 'react';
import BootstrapTable from 'react-bootstrap-table-next';
class BundleShipping extends React.Component {
constructor(props) {
super(props)
this.state = {
pickTicket: '',
Pallets: [],
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({ pickTicket: event.target.value });
}
handleSubmit(event) {
this.GetParametersPickTicket('016683O01', 'en-US', 'e3eda398-4f2a-491f-8c8e-e88f3e369a5c')
.then((responseData) => { this.setState({ Pallet: responseData.Data.Pallet }) })
.then((response) => console.log(response))
}
GetParametersPickTicket(PickTicket, language, Plant) {
console.log(PickTicket)
console.log(language)
console.log(Plant)
return fetch('http://localhost:55805/api/GicoBundleWA/GetParametersPickTicket', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
pickTicket_str: PickTicket,
kPlant: Plant,
language: language
}),
}).then((response) => response.json())
.then((responseJson) => { console.log(JSON.stringify(responseJson)) })
.catch((err) => console.log(err))
}
render() {
const columns = [{
dataField: 'PalletNumber',
text: 'Estibas Cargadas'
}, {
dataField: 'Quantity',
text: 'Cantidad'
}, {
dataField: 'Bundles',
text: 'Bultos'
}, {
dataField: 'Date_Time',
text: 'Fecha de carga'
}];
return (
<div className="container">
<form onSubmit={this.handleSubmit}>
<div className="col-lg-2 col-md-2 col-xs-3">
<label>Shipping</label>
</div>
<div className="form-group col-lg-5 col-md-5 col-xs-5">
<input type="text" value={this.state.pickTicket} onChange={this.handleChange} className="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter Pick Ticket" />
</div>
<button type="submit" className="btn btn-primary">Submit</button>
</form>
<BootstrapTable keyField='PalletNumber' data={this.state.Pallets} columns={columns} />
</div>
)
}
}
but onclick in the button not show data in console, only show it
016683O01 VM494 bundle.js:67423
en-US VM494 bundle.js:67424
e3eda398-4f2a-491f-8c8e-e88f3e369a5c VM494 bundle.js:67425
Navigated to http://localhost:3000/xxxx?
react-dom.development.js:17286 Download the React DevTools for a better development experience:
I did some tests for discover my error, for example execute code directly in console so:
function GetParametersPickTicket(PickTicket, language, Plant) {
console.log(PickTicket)
console.log(language)
console.log(Plant)
return fetch('http://localhost:xxx/api/XXX/YYYY', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
pickTicket_str: PickTicket,
kPlant: Plant,
language: language
}),
}).then((response) => response.json())
.then((responseJson) => { console.log(JSON.stringify(responseJson)) })
.catch((err) => console.log(err))
}
GetParametersPickTicket('016683O01', 'en-US', 'e3eda398-4f2a-491f-8c8e-e88f3e369a5c')
and this one if it shows my answer json.
Additionally, i resolved issue with cors, and try with postman and it show
access-control-allow-origin →*
I don't understand, why in component react does not show any result
First problem is that your method GetParametersPickTicket simply logs the received json, but it never returns it. So, the consumer of this method will simply receive an empty resolved promise. See my comment "This part was missing" in the following snippet:
GetParametersPickTicket(PickTicket, language, Plant) {
return fetch('http://localhost:55805/api/GicoBundleWA/GetParametersPickTicket', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
pickTicket_str: PickTicket,
kPlant: Plant,
language: language
}),
}).then((response) => response.json())
.then((responseJson) => {
console.log(JSON.stringify(responseJson)
return responseJson // <-- This part was missing
})
.catch((err) => console.log(err))
}
Second problem is that you're getting redirected when your form is submitted, am I right? Thus, you need prevent this default form behaviour by adding a event.preventDefault() in the beginning of your handleSubmit method:
handleSubmit(event) {
event.preventDefault()
// ... other code here
}

React form submit is creating phantom parameters

I have a basic registration form in a React front end app, that sends the input parameters to a rails-api backend.
The function to do so looks like this:
handleSubmit(event) {
event.preventDefault();
Axios.post('http://localhost:3001/auth/', {
'password': 'password',
'password_confirmation': 'password',
'email': 'asdf#asdf',
'first_name': 'asdfasdf',
'last_name': 'wefawa',
'handle': 'awfewwe'
})
.then(function (response) {
alert(response);
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
When I send this though, the params on the rails-api backend somehow include a second copy of each parameter, nested under the key "registrations" The full text, copied from console logs:
"Started POST "/auth/" for ::1 at 2018-01-12 00:36:07 -0500
Processing by Overrides::RegistrationsController#create as HTML
Parameters: {"password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "email"=>"asdf#asdf", "first_name"=>"asdfasdf", "last_name"=>"wefawa", "handle"=>"awfewwe", "registration"=>{"password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "email"=>"asdf#asdf", "first_name"=>"asdfasdf", "last_name"=>"wefawa", "handle"=>"awfewwe"}}"
Any idea where that registration tag is coming from?
I realize this is a rather specific question, but any help is much appreciated.
Thanks!
My Own Answer
I had to rearrange the syntax somewhat, but the following worked:
handleSubmit(event) {
event.preventDefault();
Axios.request({
url: 'http://localhost:3001/auth/',
method: 'post',
params: {
'password': 'password',
'password_confirmation': 'password',
'email': 'possible2#example.com',
'first_name': 'asdfasdf',
'last_name': 'wefawa',
'handle': '#notusedyet2'
},
headers: {
'Content-Type': 'multipart/form-data'
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}

How to add a BearerToken to React API Requests?

newbie to React looking for some help... I'm using React to make API requests like so:
class CatsApi {
static createCat(cat) {
const request = new Request('http://localhost:4300/api/v1/cats', {
method: 'POST',
headers: new Headers({
'Content-Type': 'application/json'
}),
body: JSON.stringify(cat)
});
return fetch(request).then(response => {
return response.json();
}).catch(error => {
return error;
});
}
Meanwhile, I have authentication to my API via react-devise:
https://github.com/timscott/react-devise
Which has a method getBearerToken like so: https://github.com/timscott/react-devise/blob/master/src/actions/authTokenStore.js
How do I use getBearerToken to pass the API the token so API requests are authenticated with the token?
Thank you!
You can use the Authorization header like:
{ 'Authorization': `Bearer ${authToken}` }
Using fetch you could try with something like:
fetch('http://localhost:4300/api/v1/cats', {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`
'Accept' : 'application/json',
'Content-Type' : 'application/json',
},
body: JSON.stringify({
cat : cat_value,
})
})
.then((response) => response.json())
.then((responseData) => { console.log(responseData) })
.catch((error) => { console.log(error) })
.done()
Also, it'd be great to see what's the Rails output in the console when you make a request, or the browser console.

React Native fetch "unsupported BodyInit type"

I'm trying to send a POST request to the OneSignal REST API using fetch:
var obj = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
'app_id': '(API KEY)',
'contents': {"en": "English Message"},
'app_ids': ["APP IDS"],
'data': {'foo': 'bar'}
})
}
fetch('https://onesignal.com/api/v1/notifications', obj)
I know you're not really supposed to put your API key in client code, but this is just a test to see if it would work. Besides, the error I'm getting isn't a bad response from the server, it's:
Possible Unhandled Promise Rejection (id: 0):
unsupported BodyInit type
I've tried putting a catch method on the fetch, but it doesn't get called.
At a bit of a loss, not really sure how to proceed.
Thanks in advance!
Even I tried the same POST request for One-Signal REST API for creating notifications,the below worked for me fine.
const bodyObj = {
app_id: "**********",
included_segments: ["All"],
data: {"foo": "bar"},
contents: {"en": "Hi good morning"}
}
fetch('https://onesignal.com/api/v1/notifications',{
method:'POST',
headers:{
'Authorization':'Basic **********',
'Content-Type':'application/json'
},
body:JSON.stringify(bodyObj)
})
.then((response) => response.json())
.then((responseJson) => {
console.log("success api call");
})
.catch((error) => {
console.error(error);
});
Have you tried to change your json to the one below?
JSON.stringify({
app_id: '(API KEY)',
contents: {en: "English Message"},
app_ids: ["APP IDS"],
data: {foo: 'bar'}
})
Or even tried a simpler json?

Resources