Angular resource not returning error response - angularjs

I'm having this trouble of handling error responses in AngularJS while using $resource. My setup works perfectly with status 200 responses, but when the API throws out a 400 error I just get an empty object.
This is my controller:
$scope.createProduct = function() {
Api.product.save($scope.product).$promise.then(
function(res) {
console.log(res);
},
function(error) {
console.log(error);
}
)
}
This is my Api service:
function ApiService($resource, API_URL) {
return {
product: $resource(
API_URL + '/product/:product_id', { 'product_id': '#product_id' },
{
show: { method: 'GET' },
update: { method: 'PUT', headers: {'Content-Type': 'application/json'} },
}
),
}
}
This is what console.log(error) prints out after a 400 error:
Object {data: null, status: -1, config: Object, statusText: ""}
And finally this is the error response API spits out which I don't get:
{
"errors": {
"message": [
"The town field is required.",
"The postcode field is required.",
]
}
}
Any help would be appreciated, thanks!
EDIT: As an example try sending a POST request to https://api.twitter.com/1.1/statuses/destroy/1.json. If I do this on Postman, I get this error message:
{
"errors": [
{
"code": 215,
"message": "Bad Authentication data."
}
]
}
How do I get this response and the string "Bad Authentication data." in Angular? For some reason I can not do this with my current setup.

The issue may relate to interactions between your API server and CORS.
I am running a Flask based API backend that was presenting this same issue. Troubleshooting led me to discovering that my API was performing a TCP RST when receiving the POST request in around 9 out of 10 connections.
Wireshark capture
The Flask server was logging that the response was being sent back correctly.
2018-08-19 13:26:59,104 INFO: 127.0.0.1 - - [19/Aug/2018 13:26:59] "POST /users/test HTTP/1.1" 419]
Cause
The the cause of the issue was rejecting the POST request in the API backend without reading the POST data first. I refactored my API to always read POST data and this solved the problem.
It's not clear to me how CORS effects this situation, however this problem was only seen when making calls through Angular instead of directly to the API.
The following StackOverflow question pointed me in the right direction to solve this.
No response with POST request and Content-Type "application/json" in flask

Related

I keep getting status 400 bad request

I am trying to use fetch function with post method to send some data to an api endpoint which is in my local, the problem is when I used client side to test the endpoint & the link I got successful response , however when I use it in my react app I keep getting status 400 bad request
what do you think the problem is?
my request code in my app:
const onClick=async()=>{
try{
let result=await fetch("http://127.0.0.1:3000/api/send",{
method:"POST",
headers:{
"Accept":"application/json",
"Content-type":"application/json;",
},
body:{
"emails": [
"aaa#aaa.com",
"bbb#bbb.com"
]
}
});

Expressjs Server cannot handle Requests from the Outside

I have a ExpressJs Server with React Components. And the Server should handle Requests from Outside and one request should play a Song from the Spotify API when not currently playing.
app.post("/play", (req, res) => {
try {
// requesting to play uses query params
id = req.query.id;
currPlayingID = 0;
// get the currently playing song from the SPotify API
axios({
url: "https://api.spotify.com/v1/me/player/currently-playing",
method: "get",
headers: {
authorization: `Bearer ${access_token}`,
},
})
// set the currently Playing ID or to zero if nothing is playing
.then((response) => {
if (response.data !== null) {
currPlayingID = response.data.id;
} else {
currPlayingID = 0;
}
});
// only play the song if its not currently playing
if (id !== currPlayingID) {
// making a axios request to the Spotify API to play the Song with the ID
axios({
url: "https://api.spotify.com/v1/me/player/play/",
method: "put",
headers: {
authorization: `Bearer ${access_token}`,
},
data: {
uris: [`spotify:track:${id}`],
},
});
res.status(204);
}
} catch (error) {
res
.status(404)
.json({ message: "Couldn't get Info from Spotify API", error: error });
}
});
The Problem:
The Code works when I start the server on the device itself (so a local server on my Desktop PC), but when I start the Server on my RaspberryPI i cannot handle Requests to this endpoint /play. Yeah I updated all the IP Adresses, everywhere.
But the moer ointeresting part is using the React Client I get this error:
Failed to load resource: net::ERR_CONNECTION_REFUSED
Requesting with POSTMAN I get the following:
Mixed Content Error: The request has been blocked because it requested an insecure HTTP resource
And from a request using a python script I get on the server side:
[UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "AxiosError: Request failed with status code 400".] {
code: 'ERR_UNHANDLED_REJECTION'
}
I have no clue how to fix each error and if it is one fix. Basically I found out it is a Problem with rejeccting requests from outside localhost, because with cURL on my ssh terminal it works.
I'm learning express, so I m not an expert, but I'm looking at your errors. I will suggest you try asyncHandler module. It handles asynchronous requests and exceptions.
I faced a similar issue because while I'm sending the API request via
Axios, my token is null/empty/wrong, so make sure your token is correct
this is my request format
axios({
method:"POST",
url:"https://graph.facebook.com/v13.0/"+phon_no_id+"/message?access_token="+token,
data:{
messaging_product:"whatsapp",
to:from,
text:{
body:"Hi.. I'm Prasath"
}
},
headers:{
"Content-Type":"application/json"
}
});

How to send body data with headers with axios get request

I am trying to get request from api that has a owner = value and date = value. Using Postman I can send a request with body json to get results. However when using Axios I can not get the results. How do I send body json to header and get results back. with Axios I am getting an empty response
does not work
var searchRecord = {
owner: 'wxTWH8zqSwaIXPAVsjZoRCkvjx73',
date: '2021-09-02',
};
var config = {
method: 'get',
url: 'http://localhost:3000/records/owner',
headers: {
'Content-Type': 'application/json',
},
body: searchRecord,
};
axios
.get('http://localhost:3000/records/owner', config)
.then(function (response) {
// handle success
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
})
in Postman I can send the following in the body and get the results I need
{
owner: 'wxTWH8zqSwaIXPAVsjZoRCkvjx73',
date: '2021-09-02',
}
output response will be:
{
"instantMessage": "false",
"isComplete": false,
"_id": "612e5cede496ce8f1b6a244c",
"date": "2021-08-31",
"title": "Ming first",
"description": "Test",
"remindTime": "1630432800",
"owner": "wxTWH8zqSwaIXPAVsjZoRCkvjx73",
}
I think I have the same problem.
When I'm using the postman to test my backend - everything work ok.
So the purpose is to get data from endpoint (and as body I want to provide user email):
data = {
"user_email": test#test.com
}
.get("api/test_endpoint/", config, data)
How to send body data and headers with axios get request?
Last comment in above topick "GET Body is allowed by the standards past 2014".
So finally is it possible or is it a correct practice?
Edit:
Of course I have to add:
It's possible to add needed data as part of get request url (but it's could not be login or pass!!!)
So for example logged in admin user has possibility to get data for some user via email like:
get('localhost/api/test_endpoint?user_email=test#test.com')
So why not use body as part of get request?

.. from origin .. has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status

I'm fairly new to making API requests. I'm am trying to set up an incoming slack webhook using a simple axios post request from my React project, however I keep receiving the CORS policy error. The request works perfectly in insomnia.
I'm using ngrok to expose my web server running on my local machine to the internet (I assumed this would correct the issue.) So I'm making the request from https://...ngrok.io, however I'm still receiving 'Status Code: 400' in my network tab along with the error above.
axios({
method: "post",
url:
"https://hooks.slack.com/services/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",
headers: { "Content-type": "application/json" },
data: { text: "Hello, World!" },
}).then(
(response) => {
console.log(response);
},
(error) => {
console.log(error);
}
);
};
There are similar errors on stackoverflow, but none fix my error. I'd really like to understand why this is happening so any advice would be appreciated.
Fixed it, for those having the same issue:
What worked for me is setting Content-Type header to application/x-www-form-urlencoded. found it in this thread: https://github.com/axios/axios/issues/475 It appears that this triggers "simple request" and therefore avoids triggering CORS preflight. https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Simple_requests

POST request to Azure Functions App to be send twice before success in React (Axios, Fetch)

I have a simple upload form which onsbubmit should post data to API. In my previous question I struggled to get it running in general, but now CORS went into play. After spending hours on configuring CORS back an forth on Azure Function I got stuck. Finally I managed to verify the server with Curl (Allow Access Origin is matching). This made me thinking there is a bug/feature in how axios handles the requests. So I used fetch just before axios. When deployed one POST fire was successful. I thought I found the problem - so I commented out the axios part. Deployed again. Nothing. So I am back with the working solution but really dirty - one of the methods is firing Error. The other is working. I think the working one is the second one. Any ideas what is happening here?
Here is my code snippet:
formHandler() {
const { formFields } = this.state;
console.log(formFields);
const response = fetch('https://example.com', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(formFields),
})
axios({
url: 'https://example.com',
method: 'post',
headers: { 'Content-Type': 'application/json'},
data: formFields
}).then(function(response){
console.log(response);
//Perform action based on response
})
.catch(function(error){
alert(error);
console.log(error.status);
//Perform action based on error
});
}
}
and this is the function.json content on Azure:
{ "bindings": [ { "authLevel": "function", "type": "httpTrigger", "direction": "in", "name": "req" }, { "type": "http", "direction": "out", "name": "res" } ] }
I have enabled the methods in the platform features of Azure Function. Should this automatically propagate to function.json? Or should I add this manually?
Axios sends an OPTIONS request prior to sending the POST. It's likely that the Azure Function is denying the OPTIONS request, which prevents the POST request from being successful. Read more about the OPTIONS verb here and here. However, it looks like your function.json is missing a methods key that should have a value of [ "options", "get", "post" ]. This will explicitly allow both OPTIONS and POST (as well as GET).
Your Azure Function's function.json should be something like this:
{
"bindings": [
{
"authLevel": "function",
"type": "httpTrigger",
"direction": "in",
"name": "req",
"methods": [
"options",
"get",
"post"
]
},
{
"type": "http",
"direction": "out",
"name": "res"
}
]
}
For all those who struggle with similar issue the workaround is relatively simple. Stick to content-type application/x-www-form-urlencoded and avoid custom headers, this way it will not force preflight with OPTIONS.
There seems to be a bug either in Axios package and/or Azure Functions on handling posting/responding to OPTIONS call. Check out: https://medium.com/#praveen.beatle/avoiding-pre-flight-options-calls-on-cors-requests-baba9692c21a
for some other related hints.
In firefox I noticed that Option call from Localhost has Origin: null. This maybe AXIOS bug and Azure Function does not accept this call as proper Options call. But I stopped further investigation on his.

Resources