Ionic V3 Request randomly fail in Chrome Browser and Emulator - asp.net-core

I have a weird problem with Http-Requests randomly failing with an Ionic(V3) App using the Http-Client from Angular (7.1.1).
The Backend is an ASP.NET Core Web API with CORS configured to allow any Headers, Methods and Origins.
To figure out the problem I switched from Emulator to Browser. After resolving some CORS Issues I noticed that the problem with failing requests only exists in Chrome (FF and Edge are working fine).
The HTTP Requests fail with: "ERR_INVALID_HTTP_RESPONSE", after clicking back and forth the network tab looks like this:
I can't explain why some Requests don't have the Preflight request, but those requests seem to always succeed (they also have den header "Accept: application/json, text/plain, /" which should alway trigger the Options-Preflight, if I am correct?)
Also every requests, even the failing ones, reach the backend and resolve successfully on the backend.
The error on the client in the console:
{
"headers": {
"normalizedNames": {},
"lazyUpdate": null,
"headers": {}
},
"status": 0,
"statusText": "Unknown Error",
"url": null,
"ok": false,
"name": "HttpErrorResponse",
"message": "Http failure response for (unknown url): 0 Unknown Error",
"error": {
"isTrusted": true
}
}
Reading the Ionic forums this leads to a CORS problem. Perhaps I overlooked something, so here is my CORS-Configuration from the Backend:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseCors(builder =>
{
builder.WithOrigins("*")
.WithMethods("*")
.WithHeaders("*");
});
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseMvc();
}
Any hint is really appreciated.

If your Web API project is on aspnet core 2.2 then it could be related to this issue:
Response that returns 204 fails with HTTP_1_1_REQUIRED/INVALID_HTTP_RESPONSE in ANCM In-process
There is three options:
Downgrade to aspnetcore 2.1
Upgrade to 2.2.1 / 3.0.0 preview
Use the work around mentioned on the issue:
Add the following as the first lines of your StartUp.cs Configure method.
app.Use(async (ctx, next) =>
{
await next();
if (ctx.Response.StatusCode == 204)
{
ctx.Response.ContentLength = 0;
}
});
Also about the preflight not firing everytime, the browser cache includes the results of preflight OPTIONS calls so instead of having to fire a preflight on every request, it only fires once the cache has expired.
Lastly: configuring CORS with an accept of any origin can be unsafe, see:CORS security: reflecting any origin header value when configured to * is dangerous

Related

Ionic 6 API REST post method headers

I'm trying to make a API REST Request but i can't connect with the api, i'd trying different options but i could do it.
This is my ts
post(emplead2){
let data = {
"LastName": this.LastName
}
this.proveedor.addStudent(data)
.subscribe(
(data)=>{this.empleados = data;},
(error)=>{console.log(error);}
)
}
this is my service
addStudent(data): Observable<any> {
const headers = new HttpHeaders().append('Content-Type','application/json');
const body = 'hola';
console.log(body)
console.log(headers)
return this.http.post('APIURL',body,{headers: headers});
}
this is the error
Access to XMLHttpRequest at 'MYAPIURL' from origin 'http://localhost:8100' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
The problem here is not from your ionic application or how you are sending the POST request. What is basically happening is that your http request is being blocked by CORS policy for security reasons. You can check here what exactly is CORS policy and why it is blocking your request.
Fixing this depends on the language/framework you built the API with, but what you need to do is allow your ionic application's base url (http://localhost:8100) to access the API and bypass the CORS policy.

NUXT Redirect issue when making a POST request to external API

I have a form that I built in Nuxt. I'm trying to submit it to an external API. The expected response is a JWT token.
async login() {
const res = await this.$axios.$post(`/api/token`, {
username: this.username,
password: this.password
}, this.headers )
console.log(res)
}
Trying to call the API directly gets me a CORS error, so I use proxy settings in my nuxt.confix.js.
...
modules: [
'#nuxtjs/axios',
'#nuxtjs/proxy'
],
axios: {
baseURL: '/',
proxy: true
},
proxy: {
'/api/': { target: 'https://<apiurl>.com/', changeOrigin: true }
},
...
Now when I check the network tab, it shows a 301 redirect, but the data that was sent in the post request gets thrown away, and it makes a get request to the API which returns a 405 error (because it's expecting a POST request with a data and not an empty GET request).
How can I make a POST request to an external API using NUXT? Is this an option at all?
I tried changing changeOrigin: false, and that seems to get rid of the issue, but it throws a 500 server error instead and an npm error that says
ERROR [HPM] Error occurred while proxying request localhost:3000/api/token to https://<apiurl>.com/ [ERR_TLS_CERT_ALTNAME_INVALID] (https://nodejs.org/api/errors.html#errors_common_system_errors)
Thank you
The problem is not how to send api to an external API ... the problem is in the external API it self ... make sure the external API has no credentials required to make any action ...
if you can make a request to https://jsonplaceholder.typicode.com/posts and get results that means there is no problems in your code ... cors erros in most cases are backend issue ... which means .. the backend developer who worked on it should fix it

CORS blocking requests in Kotlin lambda but not in identically setup Node lambda

I have a lambda, written in Kotlin with Serverless and CORS just is not working. I feel like I've tried everything. I deployed a Node Lambda with identical sls.sh command and yaml files. The function looks like this
hello:
handler: handler.hello
events:
- http:
path: hello
method: post
cors: true
My responses look like this in both Node and Kotlin:
{
"statusCode": 200,
"headers": {
"Access-Control-Allow-Origin": "*"
},
"body": "{\"id\": \"f9f76590-xxxx-xxxx-xxxx-9c8e99238f40\"}"
}
In the Node case this all works great. I make a fetch call like this and it works (omitted the Promise resolutions for brevity):
var makeRequest = function (data) {
fetch('https://{lambda URL}/hello', {
'headers': {
'content-type': 'application/json'
},
'body': JSON.stringify({ data }),
'method': 'POST'
})
}
In the Kotlin case I get this CORS error back
Access to fetch at 'https://{lambda URL}/hello' from origin
'http://127.0.0.1:8080' has been blocked by CORS policy: No
'Access-Control-Allow-Origin' header is present on the requested
resource. If an opaque response serves your needs, set the request's
mode to 'no-cors' to fetch the resource with CORS disabled.
I try to "enable CORS" in the API Gateway panel but I get that it's already enabled:
And hit submit I get the error (invalid response status code)
When I hover over the error icon it says "Invalid Response status code specified".
Under Gateway Responses, under every sub item (Default 4XX, Default 5XXX, etc) there are response headers set. This is the same across my Node and Kotlin lambdas.
I'm completely out of ideas at this point.
The only potentially odd thing is I am noticing that in my Node request I see access-control-allow-origin: * in response headers in the browser network panel but in the Kotlin one I don't see it.
From this:
I can see that you haven't created Integration Response in your post method.
Try these configurations:
I discovered my CORS issue was because of server errors. If your server has an error and the API Gateway can't get a response then you get a CORS error because the Gateway itself doesn't have the CORS headers.
While the fix is easy (just handle that server error) it was hard to uncover. I wish this was documented better somewhere so hopefully this is found for others :)
For my case specifically, and why it didn't show up in Node but showed up in Kotlin, was because of types. the browser was sending a type Node automatically corrected the type (number to string) but Kotlin was expecting the type and threw a type error.

Lyft-API - GET from Localhost

I have been trying to figure out how to get this Vue project to work with the Lyft API. I have been able to get an Auth Token successfully created from the three-legged procedure, but I am unable to get the available drive types https://api.lyft.com/v1/ridetypes endpoint from the localhost:8080. It does work on Postman.
It keeps stating:
Access to XMLHttpRequest at
'https://api.lyft.com/v1/ridetypes?lat=37.7752315&lng=-122.418075'
from origin 'http://localhost:8080' has been blocked by CORS policy:
Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource.
I had tried doing a proxy using a vue.config.js file:
module.exports = {
devServer: {
proxy: {
'/lyftapi': {
target: 'https://api.lyft.com/v1',
ws: true,
changeOrigin: true
}
}
}
}
I been around other parts of Stack Overflow, and this is the closest thing to my problem, but no answers.
CORS error in Lyft API started recently
Any suggestions?
Axios Get Call
axios.get('/ridetypes', {
baseURL: 'https://api.lyft.com/v1',
headers: {
'Authorization': this.lyftToken,
},
params: {
lat: lat.toString(),
lng: long.toString()
}
})
If it means anything, I am able to make successful GET calls to retrieve Uber products, but not so much the Auth Token (unless its from Postman).
Lyft-API has disabled CORS, this means that browsers will block calls to api.lyft.com.
Vue won't be able to do anyting about this as this is a browser security policy.
Luckily there is nothing from stoping you to make this call from your own server.
One solution is to forward the request and response using your own server. You make a call to your server, the server makes a call to lyft, waits for the response and then responds your request.
This is not a vue only solution.

Uber sandbox'ed /requests endpoint uses production environment and call real drivers

This behavior started today (11/10/2015).
When I make a call to sandboxed Uber endpoint a real driver accept and comes.
I've spent 5 hours trying to understand what is happening.
I've been using Uber API for last 1.5 months and haven't had this issue before.
I make this request (now I do it with Postman, so seems like there is nothing else can affect it):
URL: https://sandbox-api.uber.com/v1/requests
Method: POST
Headers:
Authorization Bearer AvwkOYENiYRS... (Got it from Uber)
Content-Type: application/json
body:
{
"product_id": "04a497f5-380d-47f2-bf1b-ad4cfdcb51f2", // got from uber before that
"start_latitude":37.4237323,
"start_longitude":-122.09827279999999,
"end_latitude":37.4243272,
"end_longitude":-122.09491579999997
}
I receive successful response from Uber.
And after some time server start receiving events from Uber:
X-Environment: production
{
...
"event_type": "requests.status_changed",
"meta": {
"resource_id": "...", // resource_id that I get when requested sandboxed api
"status": "accepted" // and then arriving, etc
},
...
}
This was a bug on Uber's side. This was resolved this morning. Let us know if you still see the issue.