process.env adding undefined after itself - javascript

I'm having a really strange interaction with my env file when trying to use it in a fetch request.
.env:
URL = http://localhost:3000/
fetch request:
fetch(`${process.env.URL}api/data`,{})
return:
http://localhost:3000/undefinedapi/data
I have also tried changing the fetch request to:
fetch(`${process.env.URL}/api/data`,{})
return:
http://localhost:3000/api/data
This slightly fixed the url structure but doesn't help the act that for some reason it's adding undefined after the proccessing the env.

If you are using react-scripts all custom variables requires a prefix REACT_APP to be exposed.
Every custom variable without prefix will return undefined.
Try change the URL to REACT_APP_URL and process.env.REACT_APP_URL

Related

API path is changed when updated to newest nextjs

I have a problem, updated my app to newest nextjs (13.1.6), however all my request ar failing now. Somehow, the URL I set up in the request creator, based on the ENV value, is getting overwritten.
.env file
CONST NEXT_PUBLIC_API_URL = 'HTTPS://API.COM';
requestCreator file
const response = await fetch(process.env.NEXT_PUBLIC_API_URL);
Before updating, the requests were sent properly to URL:
https://api.com/some-path
But after nextjs update, the requests are being sent to:
http://localhost:3000/_next/data/development/en/some-path
Why does this happen? How to solve it?
To expose env to the browser his name should started with NEXT_PUBLIC_.
But this rule old enough. Maybe you used very old Next version
https://nextjs.org/docs/basic-features/environment-variables#exposing-environment-variables-to-the-browser

postman: You need to enable JavaScript to run this app

I've got a new API from the backend team in a new project, when I call the api it returns "you need to enable java...", whereas I had used Postman for another project before... is it related to api, server or something else?
I don't think that POSTMAN is capable of executing JavaScript in its console.
Try doing the same in the web browser it will work (You won't see this error message).
I spent some times pondering on this trepidation.. and then suddenly i realized what was going on..
the endpoint does not exist, it could be a misspelling
not in the same directory as you expect it to be,
try adding or removing "/" at the beginning of the url, particularly if you don't specify the hostname, i.e. fetch('getusername') is different from fetch('/getusername') .
. This acceptable in development but NOT when already deployed, it points to different path.
the endpoint may be working fine in the Development,
but somewhere within in the Production/Staging, it generated some exception.
I updated Postman and now it works. I'm not sure if it was because of the update or the restart.
I had this problem with a project built using the new template in Visual Studio 2022 for a React app with .NET Core.
In my case I was only getting the response "You need to enable JavaScript to run this app" with calls to a new controller I added. Calls to the built-in WeatherForecastController were working just fine. My new controller was configured the same as the built-in controller so I could not figure out why this was happening. It has to do with how this project template creates both a React app and a back-end API both accessible on the same port. There's a setupProxy.js file that defines routes that should be forwarded to the API. All other routes are redirected to index.html. This is actually what was happening in my case, because my new controller had not been added to setupProxy.js the middleware was redirecting the request to index.html, and because it came from Postman rather than a browser the message regarding enabling JavaScript is displayed.
The solution is that each controller must be explicitly mapped in setupProxy.js or else it won't be proxied correctly. After making this change it worked perfectly in Postman as well as fetch calls from the React app.
const context = [
"/weatherforecast", // built-in controller than comes with the project template in VS2022
"/recaptcha" // controller I created (this line must be added)
];
While calling the REST API with the postman, if you miss the end-point, then also this issue will come, add the end-point to the URL and check
What worked for me was to turn-off / deselect the user-agent header field under request

this.passthrough() functionality in Ember

I am writing an application in Ember.js and I am also using Ember mirage. I need to make requests to an external server and I am currently trying to set up my config.js file to deal with such requests. Adding this.passthrough() does not work and I still get an error when I try to make my request saying:
"Your Ember app tried to GET 'http://...' but there was no route defined to handle this request. Define a route that matches this path in your mirage/config.js file. Did you forget to add your namespace?
I believe this should be a simple thing to fix, any ideas of what is going wrong?
Mirage helpdoc explaining it detail. configuration/#passthrough
If you want all requests on the current domain to pass through, simply invoke the method with no arguments:
this.passthrough();
You can also allow other-origin hosts to passthrough. If you use a fully-qualified domain name, the namespace property will be ignored. Use two * wildcards to match all requests under a path:
this.passthrough('http://api.foo.bar/**');
Note:Put all passthrough config at the bottom of your config.js file, to give your route handlers precedence.

Angular 2, localhost/null error when trying to use http.get?

I am using Angular 2 to make a webpage. When I load the page, I use OnInit to run the following method (with generic names substituted):
getAllObjects(): Promise<object[]>{
return this.http.get(this.getAllObjectsUrl).toPromise().then(response => response.json().data).catch(this.handleError);
}
I've verified in my browser that the getAllObjects url does indeed return an array of object in JSON format. Here is the url if it is helpful:
private getAllObjectsUrl : 'http://99.240.124.235:7060/REST/rest/companyService/getAllCompanies.json/';
However, this method triggers the handleError catch and the browser's debugging log shows GET localhost:3000/null 404 NOT FOUND (I am using an npm server to run it, hence the localhost).
I do not believe it is a CORS issue because I downloaded the Chrome CORS plugin and other API calls have worked. It is only this particular API url that is causing a problem, which I find strange as my other API calls work and they follow the exact same format (except a different url).
I thought maybe the appComponent wasn't allowed an OnInit, but I replaced getAllObjects() with a different working API call, and I didn't receive this error.
I am completely stuck and any help would be appreciated (could this error be because of the web API, not the front end?).
getAllObjectsUrl doesn't contain the url because you are using colon(:) instead of equal sign(=)
Colon indicates the type of the variable, whereas equal sign initializes it.
change this
private getAllObjectsUrl : 'http://99.240.124.235:7060/REST/rest/companyService/getAllCompanies.json/';
for this
private getAllObjectsUrl = 'http://99.240.124.235:7060/REST/rest/companyService/getAllCompanies.json/';

Node process.env variables empty

I'm building my first Express app, which needs to interact with an API, using an API key that ideally remains secure.
So I wanted to follow a basic pattern of keeping the key (and any future environment variables), in a .gitignored .env file in the root directory.
To not reinvent the wheel, I used this package, and set my env variables like so, in my app.coffee file (the root file of the application):
env = require('node-env-file')
env __dirname + '/.env'
console.log process.env.MY_API_KEY
That console.log prints out the right key to the server logs. The problem arises later:
If I try to access that same variable in one of the JS files loaded later on by my app, process.env is an empty object, so the API key is undefined. This doesn't appear to be a problem with the above package, because if I define the variable in the CL (API_KEY=whatever npm start), the behavior is the same -- it console logs correctly from app.coffee but is unavailable later.
Some information on how the files in which the key is unavailable are being loaded:
The app is running React, which I write to a few .jsx files in public/javascripts/src, and which are compiled by gulp into public/javascripts/build/*.js.
I'm trying to access the key in a .js file in public/javascripts/ which is required by one of the .jsx files.
In that required .js file, process.env returns an empty object. When I try to access process.env in the .jsx files, I'm actually told that process itself is undefined.
Any ideas what's going on here? I'm new to Express/React, and unclear where this process object, which I thought was global and defined on npm start is defined, and what's happening to all the env info in it.
Thanks! Please let me know if any other information would be helpful, orif anyone has any suggestions for how better to handle private env info in my situation.
EDIT:
I tried the suggestions below, and created a separate endpoint internally, which hits the external API and then returns a response. I've strung things up correctly, so that this responds correctly:
router.get '/images', (req, res, next) ->
res.json({ some: 'json' });
but this (which uses a separate class to make a request to an external API), throws an error:
router.get '/images', (req, res, next) ->
new Images('nature').fetch (images) ->
res.json({ some: 'json' })
Essentially, it looks like the asynchrony of the response from the external API (and not even the data itself, which I ignored), is creating a problem. How do I hit this external endpoint and then respond to the internal request with the incoming data?
Back-end vs Front-end
It seems like you are trying to access back-end data from a front-end location, in a wrong way.
The great power of Node.js is having JavaScript in the front and in the back, but it is quite confusing in the beginning to understand on which side each script is executed.
In an Express project, all Javascript files that are sent to the front-end, those that will directly interact with the client's page, are located in public/javascripts/. Generally you will have some AJAX functions in some of those files to exchange data and communicate with the back-end.
These back-end files are located everywhere else : in the root directory, in routes/, and all the other folders you create. Those files are pretty much all connected to your Node instance, and therefore can communicate with each other using global objects like process for example.
Your script in public/javascripts/, that is executed on the client's computer, is trying to directly access a variable located on the server running your Node instance : that's why your code doesn't work. If you wish to access data from the back-end, you must use AJAX calls in the front-end.
Server <---(AJAX only)--- Client
------ ------
app.js public/javascripts/script.js
routes.js
...
That being said, you wanted to keep your API key private, which will not happen if you send it to every client who's on that specific page. What you should do is make the call from the back-end, using the xhr module for example, and then delivering the data to front-end, without the secret API key.
I hope I was clear, Node is quite confusing at first but very soon you will get over these little mistakes !
All .jsx is, is some code, what matters is where the code is being executed. process.env is a variable that is accessible inside the Node.js runtime. When your .jsx code gets transpiled down to .js and served to the browser, the process.env variable will no longer exist. If you're making an API call inside the browser, the API key will be fundamentally available to the client. If you want to secure the key, you have to have your Node.js server expose an API route, which your React app will hit. That Node.js server will then make the call to the external service using the API key. Because that call is being made by the server, process.env will be available, and will remain hidden from the client. You can then forward the result of the API call back to the user.

Categories

Resources