Nuxt 3 $fetch method doesn't work with golang servers? - vue.js

UPD: you can check this yourself: https://github.com/Rusinas/nuxt-fetch-bug
I know I know this sounds stupid as hell and server language has nothing to do with such problems, but hear me out.
I am trying to load data from my local server using $fetch() (or useFetch, no difference), but I get this error:
FetchError: fetch failed ()
No any other details provided. Server is running using Golang/Fiber. When I am trying to load the same endpoint via Postman, everything is OK:
But when I try to load the SAME endpoint in my nuxt 3 application:
I get this:
But my golang server logging this as success:
The more weird thing about all this is that if I run my nodejs version of the exact same server (or any other random API), I don't get any error.
I am pretty sure that my server working 100% correct, but maybe I lost some header or something, which express put automatically? Here is my response headers:
I also checked nodejs response headers:
Doesn't seem like problem is there.
I have no idea what is happening and I don't know other methods to retrieve async data on server side in nuxt js. I have installed axios, but it throws random errors and works on client side for some reason, which makes using nuxt meaningless. However, axios can call this endpoint and returns my data, but only in browser (despite I call it in setup function without any hooks). I am thinking to switch career now

The problem was that fetch() didn't reconize localhost:9000 for some
reason, but when I changed BASE_URL to 127.0.0.1:9000 it started to
work
I had the same error: FetchError: fetch failed ()
Changing localhost in the url to 127.0.0.1 worked for me.
Writing as a separate answer because some might not find it in the comments.

First I think you are using $fetch in a wrong way, as I've seen Nuxt uses fetch for example:
const data = await fetch(endpoint, {
method: "GET",
mode: "cors"
})
.then(resp => resp.json())
And for the server, just enable CORS header on the response, like this:
// you can replace the asterisk with the clients you want.
c.Append("Access-Control-Allow-Origin", "*")
hope I helped :)

Related

Can Cypress intercept requests being made directly to a server?

I have been trying to intercept a server request using Cypress' intercept method.
I have noticed that Cypress can intercept requests made through the front-end/browser, however, the intercept method doesn't work if I make a request directly to the back-end server.
Let me clarify what I mean:
One thing is intercepting a request that the front-end/browser makes to the back-end server.
Another thing is intercepting a call that doesn't use the browser but calls directly the back-end endpoint.
For example:
I can create a user using the front-end interface
or I can create a user calling the back-end endpoint directly (directly calling the server).
Coming back to my question. Is there a way to intercept a call that was made directly to the back-end endpoint?
This is what I have tried so far:
I wrote a regex to intercept api/v0/customers
I then made a request to http://locahost:5440/api/v0/customers (which is the URL of the server)
Finally, I waited for the request to happen
Timeout request using Cypress intercept method
cy.intercept(/^\/api\/v0\/customers\/$/).as('createCustomer');
cy.request(createCustomer(customerData, headers));
cy.wait('#createCustomer').then(({ status, body }) => {
const customerId = body.customer_id;
console.log(body);
expect(status).equal(201);
});
Here's the problem: There was a timeout error.
As you can see in the image, I'm making a request to http://locahost:5440 which is the server URL. NOTE: I made sure the server was up and running.
The regex is also correct and it will match the endpoint http://locahost:5440/api/v0/customers
I suspect that intercept only works for requests being made through the browser. Is this assertion correct? I couldn't find this answer anywhere in the Cypress docs.
Is there a way for me to intercept a call being made directly to a server (not using the browser)?
You don't have to intercept the requests you explicitly make with cypress, just use .then to get the response, like this:
cy.request(createCustomer(customerData, headers)).then((response) => {
const customerId = response.body.customer_id;
console.log(response.body);
expect(response.status).equal(201);
});
Reference: https://docs.cypress.io/api/commands/request#Yields

Express JS changing line break type to CRLF

I am trying to make a HTTP request from a Flutter App to a Express-JS Server running on an Ubuntu machine. A newer version of Flutter(v1.22.5) throws following error when making the Request:
E/flutter (29477): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: Invalid response, unexpected 10 in reason phrase
The code for making the request looks like this:
final response = await http.get(
'http://XX.XX.XXX.XXX/employees', //Hiding IP address for privacy purposes
headers: {
"Content-Type": "application/json",
"Authorization": api_key,
},
);
print(response.statusCode);
I can confirm by using HTTP-Tester Insomnia that the queried URL does indeed return information.
The issue seems to be known and can be viewed here
According to the Github-Thread, the issue is due to wrong line break format in the headers.
How can I tell Express JS to use CRLF?
For anyone stumbling across this question, I fixed it by reconfiguring my API-Server. Closer inspection of this problem lead to the conclusion that neither the App nor the API was bad, due to the fact no API-Request did actually reach my API-Code. I figured it out by simply looking at the logs. In my case, it was NginX not working properly as a reverse-proxy. I followed this tutorial to properly set it put.

Cross-Origin Request Blocked error in HTTPS request

I have a standard HTTPS Axios request from my Frontend (which is based on Vue), to the our company's API which is on another server(server use SSL sertificate).
testApi() {
axios.get('https://rng-hub2.staging.rng:8001/rng/3/')
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})
.finally(function () {
// always executed
});
},
Which cause an error like this:
In Firefox:
In Chrome the error looks like this:
As I was thinking, in browsed developing tools under tab of Netwerk -> Response, I should also see an error, which is true for Chrome, but eventyally is not true for Firefox.
So Chrome shows me:
But in the Firefox I receive my data in exactly right format:
Have any idea how I can retrieve this data correctly and assign it to the response variable in .then section?
About Cross-Origin Request Blocked error: API's server administrator told me, that he have added my IP to the CORS "trusted list". However I'm not sure, because according to this post: https://jonhilton.net/cross-origin-request-blocked/
in my Response Header I should receive an additional header with my local IP like:
Access-Control-Allow-Origin: http://192.168.32.44
But I'm not.
This proxy staff also didn't work:
How to deal with CORS error on Vue CLI 3?
Please give me hint what am I doing wrong
Found the solution. The problem was deeper then I thought. So short answer is: If you are working in local network, with different API servers, they might be certified with inner corporate CA (Certificate authority) to be able to communicate via HTTPS protocol. So what you need is, to ask from your server administrator to give you private_key with which you gonna sign all the request to a specific API. In guzzle its looks like this:
new GuzzleClient(['verify' => '/path/to/self-signed/cert.pem']);

Why can't add headers to axios.get?

I'm using axios and vue.js to play with the Fortnite Tracker API.
In their documentation it's clearly said that we need to include the "TRN-Api-Key" in header.
I tested with Postman and It works.
And this is my axios function to make the request:
let url = `https://api.fortnitetracker.com/v1/profile/${this.platform}/${this.username}`;
// username and platform are from my Vue Component.
axios.get(url, {
headers: {
"TRN-Api-Key": "xxxxxxxx-xxxx-xxxx-xxxx-xxxx" // of course from my account on their website.
}
})
.then(response => console.log(response.data))
I expect the output in json like in Postman but I had a 404 Error: "Network Error".
And in the Browser Network Debug I can't see the request header 'TRN-Api-Key'.
[EDIT]
If your app is running on a server you can write a short PHP-Script and use curl in it to access the API (I think it's even possible to generate PHPcode from Postman).
Just address this script with axios and submit your platform and usernameproperties to build the right url.
Or have a look at this post alternatively. Maybe the use of an other API like #kecinotrab provided in the acceptet answer will help you too.

API call works locally, but fails when deployed to heroku or zeit

The HTTP GET call works fine locally, but fails when the app is deployed to heroku or zeit.
Here is the code:
const searchUrl = "https:/hn.algolia.com/api/v1/search?query=" + searchTerm;
axios({
method: "get",
url: searchUrl,
responseType: "json"
})
I'm making a call to Hackernews API. But when I open network tab while loading the app in heroku, I see it is making the call to https://evening-chamber-42563.herokuapp.com/hn.algolia.com/api/v1/search?query= (the actual url should be https://hn.algolia.com/api/v1/search?query=), somehow it is inserting evening-chamber-42563.herokuapp.com/ in between the actual URL that I've specified.
I thought it might be a problem with heroku, and deployed my app on zeit to see if it fixes the issue. Same thing again. This time it made a request to https://hackernews-clone-bgbmdyblch.now.sh/hn.algolia.com/api/v1/search?query= (hackernews-clone-bgbmdyblch.now.sh is where my app is deployed).
I tried with native fetch, and axios library. Still same issue.
Hours of google searching didn't help me, so I'm posting this here. Any help appreciated. Thanks.
Turns out there was a typo in the URL (missing a '/' after the protocol). It worked fine after correcting it.
When I called fetch in my localhost with the incorrect URL (missing '/'), the browser corrected it for me. But it created problems when the app was deployed on a cloud platform.