Why is the Fetch API not working on my machine? [duplicate] - google-chrome-devtools

My Chrome Extension performs a get request which works fine. Because testing is faster with snippets, I want to do the exact same thing in the Chrome Console or in the Chrome Snippets. Minimal example:
fetch(url, {
method: "GET"
}).then(response => response.text())
.then(html => console.log(html))
.catch(error => console.log(error))
Unfortunately, there I only get
TypeError: Failed to fetch for the error and
Failed to load resource: net::ERR_FAILED in Chrome's inline error marker
In my Chrome Extension I ran into a CORS issue so what I did in my AWS Lambda function was to set the headers to
const headers = {
'Content-Type': 'application/json',
"Access-Control-Allow-Headers" : "Content-Type",
"Access-Control-Allow-Origin" : "*",
"Access-Control-Allow-Credentials" : true
};
so I suppose CORS isn't the problem here. But I can't seem to figure out as to what differences it could make to have the requests run in the Extension vs. in the console/snippets. What could I be missing here?
I also do not see the request in AWS CloudWatch so I suppose it doesn't even leave my machine. I am testing on a Chrome User that has 0 extensions installed, same happens in incognito
To circle out any issues with my server I have also inserted the examples from https://lockevn.medium.com/snippet-to-fetch-remote-rest-api-and-display-in-console-of-chrome-devtool-6896a7cd6041
async function testGet() {
const response = await fetch('https://jsonplaceholder.typicode.com/posts')
console.log(await response.json())
}
async function testPost() {
let r = await fetch('https://jsonplaceholder.typicode.com/posts', {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
lockevn: 1
}),
})
console.log(await r.json())
}
testGet()
testPost()
Chrome's Network tab shows the request as stalled
The linked 'explanation' gives
Queueing: The browser queues requests when:
There are higher priority requests.
There are already six TCP connections open for this origin, which is
the limit. Applies to HTTP/1.0 and HTTP/1.1 only.
The browser is briefly allocating space in the disk cache
Stalled: The request could be stalled for any of the reasons described in Queueing.
Higher priority seems odd, 6 connections can't be the issue either since I have restarted my browser before testing, and the disk cache issue doesn't sound like the problem either. I'm not macOS with no anti virus

I managed to find the issue. In order to avoid potentially privileging my requests by opening the Chrome Developer Console in my AWS dashboard tab, I have created a new tab (chrome://new-tab-page/) and performed the requests in the console. This returned the errors described.
When I have updated my question with the example code I wanted to confirm if it was running before asking someone to try it if it works on their machine. For quick runtime-validation I opened the Console in the Stackoverflow tab and it worked. I only wanted to check if the code can be interpreted but it turned out to actually return a result. The same is valid for my AWS instance, if I run it on a https website it works fine. No idea why this is not documented but "disk cache" is mentioned as a potential error.
tldr don't open Chrome Console in new tab for requests in the console, use any website. This may have to do with CORS headers only working if the request doesn't have empty headers to begin with maybe (?)
I specifically avoided using a website console instance for testing because I wanted to prevent potential cookies on the AWS page from doing something that someone else couldn't do on their machine. Good thinking bad result haha
Thank you so much for your comments suggesting the help, much appreciated.

Related

Cross-Origin Request Blocked in any browser eventhough supported

I have already read a lot of other stackoverflow questions and github issues but none were able to resolve my issue so i decided to open a new one.
I am building a short application with Nextjs (frontend) and Express+Node (backend). Everytime the Frontend makes a get/post request to the backend via REST I get
"Cross-Origin Request Blocked: The Same Origin Policy disallows
reading the remote resource at DOMAIN. (Reason: CORS header
'Access-Control-Allow-Origin' missing)."
To fix this, i tried multiple things. First of all i added app.use(cors()) in my backend, but that didnt work. I added
const configcors = {
origin: true,
methods: 'GET,HEAD,POST,PUT,DELETE,CONNECT,OPTIONS,TRACE,PATCH',
allowedHeaders: 'X-Powered-By,Content-Type,Content-Length,ETag,Date,Connection,Keep-Alive',
exposedHeaders: 'X-Powered-By,Content-Type,Content-Length,ETag,Date,Connection,Keep-Alive',
credentials: true
}
app.use(cors(configcors))
to allow absolutely everything but that didnt work either. i tried to add the headers manually using
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
next();
});
which - as you might expect - didnt work either.
Lastly i thought if maybe there was an error with the preflight, so i tried
app.options('*', cors(configcors))
which didnt work either. Furthermore, trying to solve the problem, i looked at the network tab, to identify the headers and whether the correct headers were send. In Firefox there appeared no Request in the Networking Tab at all.
Chrome:
On chrome tho, i can see the request but there are no response headers at all. This let me assume that maybe CORS wasnt the problem - To try this i installed the moesif CORS extension in chrome to allow all sorts of CORS. I was wrong: with the extension enabled, every request works perfectly fine - but i cant rely on an extension in production.
This means that the error definitely has something to do with CORS but I have no idea what I should do now.
if anyone had similiar troubles i would be very thankful for your advice.
Try this:
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "http://localhost:3000");
res.header("Access-Control-Allow-Headers", "*");
next();
});

Flutter web app does not work with local golang http server

I know it sounds like a beginner's question, but here I go:
I've developed a small app to be used locally in restaurants for the waiters to be able to take orders on their phones. Pretty basic. I also developed a simple go HTTP server to implement the necessary API. It works fine on the "mobile" version, both in the emulator and actual devices.
The next step is to port the app so it can be used by the customers in their phones' browsers.
When I changed it to the web version, it worked correctly in Chrome and Edge, at least in terms of UI and navigation. But I am not able to use the API because I get the XMLHTTPError in all requests (that's what the error capture returns, I don't know how to get more details on that).
I did a little research on the matter, and one of the answers includes changing configurations in Chrome, etc., which would be impossible for the customers to do. Also, it seems that a possibility is changing the go server from HTTP to HTTPS.
This is my go lang HTTP server code (part of)
func main() {
r := mux.NewRouter()
http.Handle("/", r)
r.HandleFunc("/api/getgarcon", get_garcon).Methods("GET")
log.Fatal(http.ListenAndServe(":8000", r))
}
get_garcon is a function that returns a JSON list of the registered waiters for login. As I said before, it works correctly if the client is a mobile app.
This is the flutter/dart code in the app
Future<List<Garcon>> getGarcon() async {
var data;
try {
print(glbHttpServer + "api/getgarcon");
data = await http.get(
glbHttpServer + "api/getgarcon",
headers: {'Content-Type': 'application/json','Access-Control-Allow-Origin':'*',
'Access-Control-Allow-Methods':'HEAD, GET, POST, PUT, PATCH, DELETE, OPTIONS',
'Access-Control-Allow-Headers':'X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method,Access-Control-Request-Headers, Authorization'},
);
} catch (e) {
print("getgarcon=" + e.toString());
}
etc...
glbHttpServer is a variable whose value is like "http://192.168.29.94:8000/"
I added those headers trying to get this to work for the web app. Previously (for the mobile app) there was only the 'Content-Type': 'application/json' header.
As additional information, both the web app and the go server are on the same machine. If I type http://192.168.29.94:8000/api/getgarcon in a Chrome window (or Edge window), it works. Same with localhost or 127.0.0.1.
So what I'm asking here is: which is the least complicated way to go? Adding some different code in my app? Changing the server from HTTP to HTTPS? Or is another solution available that I haven't found?
And most important: is it worth the effort, given the current state of the flutter web?
Thanks for any help.
You need to add those CORS headers to the response on the server, not the request from Flutter. In Go, it would look like this. You can create a middleware to handle this for all your endpoints.
func main() {
http.HandleFunc("/", func (w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", ...)
w.Header().Set("Access-Control-Allow-Methods", ...)
w.Header().Set("Access-Control-Allow-Headers", ...)
...
})
...
}
Mobile apps do not have the same CORS restrictions, which is why you would not have noticed it. However, if you tried to load your Flutter website in a mobile browser, you would notice the same behavior.

axios causing an unintended OPTIONS request on HERE Autocomplete api

I am getting a preflight error 405: Method not allowed from the HERE API when I request autocomplete as per the documentation.
UPDATE 2:
I have since determined that Axios was adding my default.common authentication headers from my app's API client onto the HERE API client. Axios is supposed to keep those defaults separate per-client, but it seems that it doesn't ... at least not the version I have. I replaced the defaults with a per-client request interceptor and it worked fine. The request no longer triggers an OPTION pre-flight. No issue with HERE's API other than that it doesn't support OPTION method.
UPDATE:
The reason it fails is because HERE does not support the OPTIONS method, only the GET. So now the question is: Why does axios trigger an OPTIONS request when I don't set any headers? An XMLHttpRequest() based GET request does not trigger OPTIONS for the same URL. Something is happening with axios but I don't know what and I can't seem to investigate the headers that axios is sending.
ORIGINAL:
I've tried to find information about this error, as well as HTTP vs HTTPS. I haven't seen others having this problem so I feel like I must be making a simple error. The URL is generated correctly because it works when pasted directly into the browser for example.
const hereClient = axios.create({
baseURL: 'https://autocomplete.geocoder.api.here.com/6.2/'
})
async function searchHere (query) {
let searchTerms = query.split(' ').join('+')
let result = await hereClient.get('suggest.json', {
params: {
app_id: '<APPID>',
app_code: '<APPCODE>',
query: searchTerms
}
})
return processHereSearchResults(result.data)
}
The GET request fails on the OPTION preflight with a 405: Method not allowed. But if I paste the generated URL into a browser then it returns the expected results. For example:
https://autocomplete.geocoder.api.here.com/6.2/suggest.json?app_id=APPID&app_code=APPCODE&query=8131
returns:
{"suggestions":[{"label":"Česko, Brandýs nad Orlicí, 3123","language":"cs","countryCode":"CZE","locationId":"N . . .
Same result whether http or https.
I have since determined that Axios was adding my default.common authentication headers from my app's API client onto the HERE API client. Axios is supposed to keep those defaults separate per-client, but it seems that it doesn't ... at least not the version I have. I replaced the default header setting with a per-client request interceptor to set my authentication and it worked fine. The request no longer triggers an OPTION pre-flight. No issue with HERE's API other than that it doesn't support OPTION method.

Adobe CQ 5 Accepts Arbitrary POST Request

i know that Adobe CQ 5 was built on top of Apache Sling (which using JackRabbit). I'm a bit baffled as for why the website will accept arbitrary POST request from outside (unauthenticated user) into Publish Instance through the Dispatcher and then reply with HTTP 200 Content Updated. Should not content update only allowed from Author Instance in this case? Should not such request met with HTTP 403 response instead? - Why is it that even not logged in can get HTTP Response 200?
The response looked like this:
{
"changes": [],
"referer": "http://www.example.com/content/somesite/en.html",
"path": "/content/somesite/en",
"location": "/content/somesite/en",
"parentLocation": "/content/somesite",
"status.code": 200,
"status.message": "OK",
"title": "Content modified /content/somesite/en"
}
I've set POST Referrer Filter for now to prevent arbitrary POST request 'outside' the website got accepted, however i can still get this response by typing jquery ajax request in the browser console while opening the website.
I do wonder if this is bad or something, really new to Adobe CQ.
The JQuery Script for testing it is actually only these:
$.ajax({
url: 'http://www.example.com/content/fasfas',
type: 'post',
data: {},
headers: {
Accept: 'application/json',
},
dataType: 'json',
success: function (data) {
console.info(data);
}
});
Thanks in advance!
This is an issue of not taking the necessary steps to secure the AEM servers. There is a security checklist provided by Adobe to ensure that AEM installation is secure when deployed. Similar security checklist for the dispatcher is also present.
As for your case, there are few issues which are evident
The filter configuration within the dispatcher doesn't deny POST
requests, thereby allowing them to pass through the dispatcher and reach the AEM instance.
The anonymous user in the AEM publisher seems to have more than just
READ privileges on the repository thereby allowing him to make changes to the repo using POST requests.
The referrer filter configuration was allowing requests from external systems as well (which you have blocked now).
Your dispatcher should block all POST operations on the publisher. This is recommended in Adobe's official documentation for configuring dispatcher.
Publisher should also disable write permission for anonymous users and everyone group to paths that are not allowed to be modified by community. Unless you are using CUG, write should be disabled for anonymous across the publisher instance.

Odd CORS error querying JIRA REST API [duplicate]

This question already has answers here:
Origin is not allowed by Access-Control-Allow-Origin
(18 answers)
Closed 6 years ago.
I am trying to develop a D3 visualisation project for our JIRA boards, but I've fallen at the first hurdle. I'm having trouble authenticating and getting a list of JIRA boards.
This code is entirely client-side and is in Angular 2 RC 3. My service looks like this:
public authenticate( username:string, password:string ):void {
let encodedAuth:string = window.btoa( `${username}:${password}` );
this.headers = new Headers();
this.headers.append( 'Content-Type', 'application/json' );
this.headers.append( 'Authorization', `Basic ${encodedAuth}` );
}
public getAllBoards():Observable<Boards> {
return this.http.get( `http://${this.host}/rest/agile/1.0/board`, this.headers )
.map( response => response.json() as Boards )
}
and the code in my component looks like this:
constructor( protected jiraService:JIRAService ) {
this.jiraService.authenticate('me#you.com', 'password');
this.jiraService.getAllBoards().subscribe(
boards => this.boards = boards
);
}
Unfortunately, this generates what looks like a CORS error in my browser:
XMLHttpRequest cannot load https://myjira.atlassian.net/rest/agile/1.0/board. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 401.
...which is a little unexpected. This same URL in the browser works fine. Examining the request in Charles I see the error "SSL Proxying not enabled for this host: enable in Proxy Settings, SSL locations", but cannot actually find this setting. I don't care if I can't see it in Charles actually, I just want to get it working!
I have tried several of the npm JIRA packages but none of them are remarkable and seem to be designed for server-side development.
Any help greatly appreciated.
You get this error when you access it from within an application that was initially loaded from a different URL. If you load a new page from this "other" URL then this is not a CORS situation because the initial page load is already from this URL.
The server need to provide the expected CORS headers for the browser to allow this request. This is not an Angular issue but only a server issue.
Workarounds are
JSONP (doesn't support custom headers)
provide support server-side where your Angular application calls to your server which then forwards to the other server and then forwards the response it gets to your Angular application.