Refused to connect to GET request - angularjs

I use an oodrive_sign service which hosts my code and which allows me to use an electronic signature
I work on AngularJS and I want to make a HTTP request.
It works locally, but in production I have this error:
ERROR
My request :
const getReq = {
method: 'GET',
url: 'https://jsonplaceholder.typicode.com/todos/1',
//headers: { 'Content-Security-Policy': 'default-src'}
};
$http.get(getReq).then(function(response){
console.log(response)
},function(err) {
console.log(err)
})
I dont know if it's my bad or if it's an error related to the oodrive service
I would like to know if I have to do anything in particular before I call them again.
Thanks

Related

How to "intercept" a request that is made with cy.request with cypress

As far as I understand cy.intercept() can be used to stub requests that the application itself makes.
Now I have a HTTP POST request with cy.request() in one of my custom commands in Cypress. Because this is a request made by cy.request() function I can't use cy.intercept() to stub the response of this request.
Is there any workaround to stub a respons of a request made with cy.request() ?
Now I have the following which is logging the real response correctly, but I want to keep this response even the when the remote server is offline:
cy.request({
method: 'POST',
url: 'https://sample.com/token',
body: {
username: "UserNameSample",
password: "PasswordSample"
},
form: true,
}).then(response => {
cy.log(JSON.stringify(response.body))
})
Which is resulting in the following printscreen of the comment log in cypress.:
You can try for fetch interface to make the network calls instead:
cy.intercept({
method: 'POST',
url: 'https://sample.com/token',
},
{
// your stubbed response
}).as('createToken').then(() => {
fetch('https://sample.com/token', {method: 'POST'})
.then((response) => {
cy.log(JSON.stringify(response.body))
})
})
cy.wait('#createToken').its('response.body')
P.S. I've not tested it, so it might need some adjustments

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"
}
});

My angular promise unexpectedly goes to error callback, why?

I have a client running on Angular + typescript.
I need to send a post request to a php API (which I developed). The request arrives correctly to the server and the server fills the response body with the correct data (I have checked it myself debugging the server).
The issue is that, when the server responds, the angular promise executes the error callback and the response data is empty. When I check the sent request in the browser it says it was answered with a 200 OK status but it has an empty body.
I have tried calling the same API endpoint with the same paramentres through Firefox Api-requester addon and i recieve the response with the correct body... why is my Angular client not succeeding then?
The following code fragment corresponds to my controller:
vm.query = {
'tx_filtre':'', 'idioma_filtre':'', 'tipus':'', 'id_dimfisica':'', 'tamPag':15, 'numPag':0
};
this.PropietatsService.getPropietats(vm.query)
.then((response: ng.IHttpPromiseCallbackArg<string>) => {
vm.objResult = JSON.parse(response.data);
vm.propietats = vm.objResult.info;
console.log('rebut', this.propietats);
}, (response: ng.IHttpPromiseCallbackArg<string>) => {
//always executes this error function, why????
vm.objResult = JSON.parse(response.data);
});
And this is the relevant code for the service:
getPropietats(query: any): ng.IPromise<ng.IHttpPromiseCallbackArg<string>> {
var config = {
headers : {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
}
};
return this.$http.post("http://localhost:8080/diccionaris/propietat/get",JSON.stringify(query),config);
}
On a side note, for some reason my server can't process the request if I set the request 'Content-Type' to 'application/json' in my client. That is the reason why I have set it to 'application/x-www-form-urlencoded'.
You set 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;', but you encode query params to JSON and then you try to decode a response like JSON. Try set application/json or try to remove JSON.encode request params and send to post method query.
If it doesn't help log error (in response) in error callback and look at it
If the server is not capable of accepting application/json, then the POST data needs to be encoded for application/x-www-form-urlencoded. To do this use the $httpParamSerializer Service:
getPropietats(query: any): ng.IPromise<ng.IHttpPromiseCallbackArg<string>> {
var config = {
headers : {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
},
transformRequest: $httpParamSerializer
};
return this.$http.post(url,query,config);
}
I finally found the solution: it was a CORS problem.
I was running my server and my client in two different localhost ports so, although the server processed the request (which doesn't make much sense to me), it wasn't returning the response because the client was not allowed to access the server. To deal with it for now I've added the following line to my server index.php:
header('Access-Control-Allow-Origin: *');
And now it works just fine.

angular and dropbox can(t get token with code flow

i have this snippet:
var req = {
method: 'POST',
url: 'https://api.dropboxapi.com/oauth2/token',
headers: {'Content-Type': 'application/json'},
data: {
'code': authCode,
'grant_type': 'authorization_code',
'client_id': 'my_id',
'client_secret': 'my_secret',
'redirect_uri':'http://localhost%3A8080/main'
}
};
return $http(req).then(function(response){
console.log(response.status);
return response;
}, function(err){
console.log(err);
});
The can always ends up in a "bad request" because ""No auth function available for given request""
The same data works with tools to send REST requests... so I don't know what I'm missing here...
Can some help?
The error message indicates that the API didn't receive the expected parameters, or at least not in a format it expected. The documentation for /1/oauth2/token say:
Calls to /oauth2/token need to be authenticated using the apps's key and secret. These can either be passed as POST parameters (see parameters below) or via HTTP basic authentication. If basic authentication is used, the app key should be provided as the username, and the app secret should be provided as the password.
You seem to be attempting to supply the parameters as JSON though, according to your Content-Type header. Try sending them as POST parameters instead.

angular $http not returning .error() variables if CORS headers are missing from the response

I'm executing an $http.get over websockets and somehow the .error doesn't populate any of the parameters. I'm using angular 1.3.5 and latest Chrome on OSX and local host is aliased to mywebsite.com.
$http({method: 'GET', 'ws://mywebsite.com/resource'})
.success(function(response){ ... })
.error(function(err, status){
console.log(err); <<< here err and status are null respectively 0 even the XHR Response logs 401 in console.
});
Any clues why this is doing so? No mater what error code it is, it doesn't get passed to error callback. For 2xx response i do get the data and all is fine.
Just to clarify, the .error callback gets called as normal, but err and status re not populated.
Well, well, I discovered what was happening. A combo of things.
First I'm using KOA and the above angular hits the KOA as REST API. I'm also using koa-jwt to auth the users and generate a token.
Now the api runs on a subdomain and even i set the CORS via koa-cors to allow * access.
The issue is that koa-jwt when the token is expired, they simply do a this.throw(401). The way KOA handles that it so immediately terminate subsequent middleware and exit with that error. THAT, didn't allow koa-cors headers to be set, regardless where I put that middleware (before or after koa-jwt).
Hence, the elegant fix was to wrap my top level yield next in a try catch and avoid allowing koa-jwt ctx.throw to propagate.
On Angular side, the browser was refusing to convey the 401 to the .error complaining it didn't find a suitable CORS to allow it to process and hand over the response :).
app.use(cors({origin:"*", methods:'GET,HEAD,PUT,POST,DELETE,PATCH'})); //allow all origins to the API.
app.use ( function *(next){
try {
yield next;
} catch (err) {
this.status = err.status || 500;
this.body = err.message;
this.app.emit('error', err, this);
}
});
... more middleware
// middleware below this line is only reached if jwt token is valid
app.use(jwt({secret: config.app.secret}));
Allowing a this.trow(401) from koa-jwt will ruin your day.
I think you just make a typo, just write like this:
$http({method: 'GET', 'ws://mywebsite.com/resource', headers: headers})
.success(function(response){ ... })
.error(function(err, status){
console.log(err);
});
However as a best practice I would do as
var request = {
method: 'GET',
url: 'ws://mywebsite.com/resource',
headers: {//insert here header you want, put Origin header only for example purposes
Origin: 'ws://mywebsite.com/resource'
}
}
$http(request)
.success(function(response){ ... })
.error(function(err, status){
console.log(err);
});
If the typo is not the error (you may copied the code) just look at this AngularJS $http error function never called

Resources