Django/React app API in production vs development? - javascript

So I have made a React app that uses Axios to fetch api's. During development, I would have an api call to 127.0.0.1. However, my ReactApp resided on localhost:3000. Therefore, it development, I can't just use:
axios.get('/api/'),
In dev I would need to use:
axios.get('127.0.0.1/api/'),
Anybody have any good ideas on how to resolve this conflict so I can see some data in dev? Kinda tough to design an UI without any data to populate it. Kinda like buying a shirt without trying it on first (which, I never try anything on, so this is a horrible analogy.)

Use it as in the first example. Because it is relative, it will resolve fine for different hosts:
axios.get('/api')
Will automatically resolve to:
// if called by https://example.com/index.js for example
"https://example.com/api"
// if called by localhost/index.js
"https(s)://localhost/api"
In your second example, if you prepend the host and port, you will get duplication!
For example, I just tried your first example on my localhost:3000 and the result is
GET http://localhost:3000/api 404 (Not Found)
Which makes sense because I don't have a /api. But did you notice it appended /api correctly after my host and port?
Now your second example:
GET http://localhost:3000/127.0.0.1/api 404 (Not Found)
It duplicates the host and port. In your case it would be 127.0.0.1:3000/127.0.0.1/api
Just use the first example and it will resolve fine for different hosts (and ports) because it's relative! Did you try it out?

Related

Axios GET request returning ECONNRESET for some URLs

I am working on an application that uses an express server to reach out to an API to fetch data. In our organisation outbound traffic requires a proxy which I have supplier to axios like below (not the real one):
let response = await axios.get(endpointUrl, {
proxy: {
host: "123.45.678.90",
port: 0000,
},
})
Passing various URLs into the axios get function returns varied results, with the following URLs returning a result:
https://www.boredapi.com/api/activity
https://api.ipify.org?format=json
https://jsonplaceholder.typicode.com/todos/1
Whereas the following URLs are returning an ECONNRESET error almost instantly:
https://api.publicapis.org/entries
https://randomuser.me/api/
https://reqres.in/api/users
I can't see any pattern between the URLs that are/are not working so wondered if a fresh set of eyes could spot the trait in them? It's important to note that all these URLs return successfully in the browser, just through this axios call being the problem.
To add to the mystery, the URLs that do work work on my machine, do work on a machine outside our organisation - so potentially a clue there?
Any help/guidance of course would be appreciated, thank you.
This error simply means that the other party closed the connection in a way that was probably not normal (or perhaps in a hurry).
For example, a socket connection may be closed by the other party abruptly for various reasons or you may have lost your wifi signal while running your application. You will then see this error/exception on your end.
What could also be the case: at random times, the other side is overloaded and simply kills the connection as a result. If that's the case, depends on what you're connecting to exactly…
Solution - This is happening because you are not listening to/handling the 'error' event. To fix this, you need to implement a listener that can handle such errors.
If the URL that work on your machine also work outside your organization and the other don't, it is most likely a problem with your proxy.
Some proxies might have configurations that makes them remove headers or change the request in a way that the target does not receive it as intended.
I also encountered a problem with axios and proxies once. I had to switch libs to make it work. To be sure, I would recommand using a lib like "request" (deprecated) juste to make sure it is not a problem with axios. There are multiple open issues on the axios repository for proxy issues.
ECONNRESET is likely occurring either because the proxy runs into some sort of error and drops the connection or the target host finds something wrong with the incoming connection and decides to immediately drop it.
That target host may either be finding a problem because of the proxy or it may be expecting something in the request that it finds is missing.
Since you have evidence that all the requests work fine when running from a different location (not through your proxy) and I can confirm that your code works fine from my location (also not running through your proxy), it definitely seems like the evidence points at your proxy as causing some problem in some requests.
One way to debug proxy issues like this is to run a request through the proxy that ends up going to some server you can debug on and see exactly what the proxy has done to the incoming request, compared to a request to that same host that doesn't go through the proxy. That will hopefully highlight some difference that you can then test to see if that's causing the problem and then eventually work on the configuration of the proxy to correct.

How to set Heroku Port for NodeJS Express App?

so I'm trying to host my website on Heroku and set up everything to get my app up and running.
Whenever I try to submit the form I get undefined errors.
Undefined Errors Console Errors
I've set it up to use the port like shown in the documenation:
app.listen(process.env.PORT || 8081, function () {
console.log('Example app listening on port 8081!');
});
When starting the app locally with heroku local web I get Typerror: Failed to Fetch and the undefined results but when I go into my .env file and add a port=8081 it works perfectly fine.
Good result
When I open it with heroku open I still have that undefined problem.
I don't really have to set a PORT in .env right? Or do I?
I read that that standard port is 80 but that didn't work either.
Can someone please help me?
Thank you!
Heres the link to the public site: https://shrouded-everglades-61993.herokuapp.com/
Here the link to my Github rep: https://github.com/stefanfeldner/capstone-travel-app
So the reason that they're undefined is that they are being set by these lines in main.js:
uiData.imageURL = data[1].imageUrl;
...
uiData.iconCode = data[0].iconCode;
Where data is the object you're retrieving from your /getData endpoint. The problem is that what /getData actually returns is [{}, {}] so of course these values are both undefined, leading to that visual broken-ness.
Now, why does /getData return these empty objects? I can't check your server logs, but there are two obvious possibilities based on the way server.js is written.
The first is that there's an error somewhere and you're simply not making it all the way to the end of your try-catch in callApi, so neither weatherData nor pixabayData are being updated.
Second, it's also possible that these calls are successful but that the desired data is not in the results, i.e. that neither of these if statements are true:
if('city_name' in data) {`
...
if('hits' in data) {
Again, in this case, neither weatherData nor pixabayData are being updated.
The way that your handler for /sendFormData is written, it doesn't check that callApi actually got any useful data, just that it has finished execution. So your code flow continues on its merry way despite the data objects still being empty.
However, there's a bigger, unrelated design flaw here: What happens if more than one person uses your website? Your client-side code calls /sendFormData, which hopefully correctly populates the global variables weatherData and pixabayData, and then separately calls /getData to try and retrieve this data.
The thing is, though, between the time your client-side calls /sendFormData and /getData, anyone else using your website could separately call /sendFormData and change the data contained in the global variables from the result of your search to the result of their search. So you'd get their search results back instead of yours, since their results overwrote your results on the server. You need to handle getting the API results and sending them back to the requester in a single transaction.
(Re: all the local Heroku Config, that's hard to answer without messing around with your local computer, sorry.)

Node URL gets "undefined" added to URL path

I have a site that exists on a dev, staging and production server. On the dev and staging server the functionality is 100% fine, however on the production server the strangest thing happens - "undefined" gets added to the URL path.
Here is the short example of what is happening:
In the index.html I have an anchor tag to logout of a session with passport: Logout.
It goes to this route on my node server:
// passport oauth logout
routes.get('/auth/logout', (req, res) => {
req.session.destroy((e) => {
req.logout();
res.redirect(config.redirects.env.prod);
});
});
On dev and staging this destroys the session and redirects you to /. On production, when you click the button it takes you to this URL randomly https://somesite.com/auth/undefined.
Any ideas on how to debug this? It is making no sense to me and there's nothing I'm finding serverside or in the markup that would cause this, especially since it is functional on dev and staging. All servers are Ubuntu servers set up exactly the same way.
I was able to resolve this. Oddly enough, 400 lines down in a completely unrelated route used for file uploads, I had a line of code that referenced config.redirects.env.production instead of config.redirects.env.prod. I wasn't even looking at that route because it wasn't even part of functionality i was testing at the moment and I saw no errors spit out (again, since the route wasnt being referenced/used yet).
Fixing that typo resolved this bizarre issue of "undefined" being inserted into the URL. Still not sure how it managed to bubble up like that.

AngularJS: Retrieving Videogular templates stored in $templateCache results 404 Error

I currently develop an AngularJS 1.5.9 Single Page Application on my localhost with NodeJS running backend, where I use
Videogular framework. http://www.videogular.com/
Everything is fine except inserting videogular object on my page. I strictly follow the given example: http://www.videogular.com/examples/simplest-videogular-player/
<videogular vg-theme="controller.config.theme.url">
<vg-media vg-src="controller.config.sources"
vg-tracks="controller.config.tracks"
vg-native-controls="true">
</vg-media>
</videogular>
But it results in AngularJS error:
(sessionId in the request is the auth token not linked to current problem)
I have found the following in videogular.js :
$templateCache.put("vg-templates/vg-media-video", "<video></video>");
$templateCache.put("vg-templates/vg-media-audio", "<audio></audio>");
I have tried to store files locally, and the error disappeared
Actually there are a lot of plugins for Videogular and they all are using $templateCache to store some files in the cache, so it would be very confusing to manually store them locally in my app folder.
How can such files be stored in the cache using $templateCache so they can be extracted properly?
I apreciate your help.
UPDATE
I have tried insert $templateCache.get to directive, where the part is loading with error 404, and it works. But still doesn't work as it supposed to be.
It seems like there is an issue with sessionId that you pass in URL parametrs, do you actually need it?
I guess your interceptor or whatever auth managing module is wrong configured, so you don't check request target URL and id parameters are going to be added for local calls as well as for backend calls.

How to use gulp-webserver proxies property?

I have a little issue with understanding of proxies of gulp-webserver package.
I need to proxy my localhost 8080 to make it accessible from the outside. But I don't quite understand how I can do it with gulp-webserver proxies property.
Here I have my piece of code:
gulp.task('server', function(){
gulp.src('dist')
.pipe(webserver({
livereload: true,
open:true,
port:8080,
proxies:[
{
source:'/hello',
target:'http://localhost:8080/hello'
}
]
}));
});
So such proxy has to give acces by simply entering the address http://localhost:8080/hello in any browser?
For what reasons this "proxies" is using?
How can I make my localhost accessible from outside with gulp?
Just answer one of you question and you should understand the rest.
To use a proxy in this development environment setup is to get around the CORS (google it). Your ajax call can not simply make a call to another domain / server address; you can actually, but your browser security policy will stop you from doing it, there are ways to get around it. And while you are developing. Most likely you have a http://localhost domain name. And the actual end point is sitting else where.
So for example in your ajax call
$http.post('/api', data);
You are actually making calls to http://localhost/api
Which doesn't exist (unless you have a full backend running). So for example you have a real backend running from http://real.com/api. By setting up the proxy with your gulp setup.
whenever you point to /api it will go out to http://real.com/api to fetch the data for you.
If you want to access the development outside your local machine. All you have to do is to set the gulp-webserver host to 0.0.0.0 then from the outside you need to find out your machine address (for example 192.168.0.1)
And from your browser on the other machine just type http://192.168.0.1:3000 (the 3000 is the property of the port) and you should able to see your local machine serving up the content.

Categories