I'm new to javascript and trying to follow a Udemy tutorial and upload the code to github along the way. I need to hide an API key used in a URL that looks like the following:
https://api.darksky.net/forecast/api-key-here/37.8267,-122.4233
I created a .env file that contains a single line API_KEY=my-key-of-numbers-here
My entire code looks like this:
const request = require('request');
require('dotenv').config();
const api_key = process.env.API_KEY;
const url = 'https://api.darksky.net/forecast/${api_key}/37.8267,-122.4233';
request({ url: url }, (error, response) => {
const data = JSON.parse(response.body);
console.log(data.currently);
});
When I run node app.js in the terminal I get back undefined. However, if I use the actual key everything works fine, but I obviously can't make the key public. How can I fix this?
try ` instead ' – Estradiaz
Per the comment by #Estradiaz. I was using an apostrophe ' around the URL instead of backticks `. Solved.
Are you sure that you have dotenv installed?
try npm install dotenv in the terminal.
Related
In my index.js file
app.use('/api/v1/users', userRouter)
In Router file
router.get("/:id", getUserDataById);
In postman:
My GET URL looks like this: http://localhost:3000/api/v1/users?id=120622
Error it gives:
Cannot GET /api/v1/users
I think, this is how query param should be given according to the docs and tutorials i followed, but this error won't go away.
If i remove query, then other endpoints work perfectly.
I am not able to catch what's going wrong here.
I am stuck with this from last 2 days.
Just a hint to resolve this, will help me a lot.
Thanks in advance!
Firstly your index.js and routes.js file is fine now you just need to send request correctly see the req.params is different and the req.query is different
First Way with (Query)
In postman:
http://localhost:3000/api/v1/users?id=120622
Your Index.
app.use('/api/v1/users', userRouter);
In Router file.
router.get("/", getUserDataById);
How did you get that id;
let id = req.query.id;
Second Way with (Params) - Look at the postman URL carefully and at Route
In postman:
http://localhost:3000/api/v1/users/120622
Your Index.
app.use('/api/v1/users', userRouter);
In Router file.
router.get("/:id", getUserDataById);
How did you get that id;
let id = req.params.id;
This is the two-way you can get your id, Let me know if you have any more questions and I'll try to clarify your points with more clarity.
You are not calling API correctly inside the Postman. You should call it like this:
http://localhost:3000/api/v1/users/120622
In the router file, what you are using is Route Parameter where the valid URL would be http://localhost:3000/api/v1/users/120622. for your Postman api to work you should remove :id at router file
I'm wondering if there's any way to listen for console messages and act on console messages when they're received. Mainly, is there any way to do this without an external module, and using the http module?
The goal is to trigger a NodeJS function or code snippet on an event like click in the HTML. If there's also a way to do this, then that's great. But once again, I'd like to do this without an external module, and just use those that are built-in to NodeJS.
Use onclick() function in JavaScript to trigger a function call when clicking on a element. Then use fetch to make a api call to the nodejs server.
I know #Haris Wilson already got the answer, but I'd just like to provide a code example.
Instead of trying to catch a console message and then execute a function if we find it, we can use fetch() to make a request to whatever URL we need, and this can allow us to make other requests.
In this case, we can use the url module and the http module to parse the url and serve the API and website, respectively.
const url = require('url')
const http = require('http')
const requestListener = async function (req, res) {
// Basic server setup
res.writeHead(200, {
'Content-Type': 'text/html'
});
res.end(/** Content here */)
// API
if (url.parse(req.url, true).pathname === '/APIcall') {
let arguments = url.parse(req.url, true).query
// Preform necassary actions here
}
}
We can now use onClick to call a function inside our webpage JavaScript, and use fetch([API URL]) to give our NodeJS data to preform an action. We can use URL params to do this, such as https://localhost:8080/APIcall?data=someData&moreParam=more-data, where ?data=someData&moreParam=more-data are the URL params.
I've started to build a typescript library (intended to be used on the server side) and right now I'm trying to use the node repl to play around with my code and see what happens in certain situations... I've built and required the file, but now I'm having a problem: I have a function that takes a http Request (type Request from express.js), and I'd like to try and run it in the repl providing it with a copy of a request that I previously made from my browser. Is this feasible?
I thought maybe I could do it by either:
doing regex magic on the request exported as cURL or
sending the request to node, but then how am I going to receive it while in the repl?
I'm not sure I understand your use-case, but you can try something like this:
In some temp folder type:
npm install "request-promise"
Then from the same temp folder, enter the REPL and type:
(async () => {const response = await require("request-promise").get("https://cnn.com"); console.log(response)})()
This example is for get, but it can be easily changed to other HTTP methods.
I've found a fairly simple way to do what I want... It involved quickly setting up a basic express server (set up following this tutorial):
mkdir scratch && cd scratch && npm init
(select defaults except entrypoint app.js)
npm i express
Create an app.js (vi app.js) with the following contents:
var express = require('express');
var app = express();
var circ = {};
circ.circ = circ;
var cache = [];
app.get('/', function (req, res) {
res.send(JSON.stringify(req, (key, value) => {
if (typeof value === 'object' && value !== null) {
// Duplicate reference found, discard key
if (cache.includes(value)) return;
// Store value in our collection
cache.push(value);
}
return value;
}));
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
(See this answer for JSON.stringify custom replacer resp. second argument to JSON.stringify). You can optionally use flatted instead, which I discovered later and is surely better.
Now do the following:
Run the app with node app.js
In your browser, navigate to the website where your desired request is posted to.
Open your browsers development tools (Ctrl+shift+c works for me).
Go to the network tab.
Find the request that interests you and right click on it.
Click on copy > copy as curl (or similar, depending on which browser you're using).
Run that curl request, but change the url it's posted to to 127.0.0.1:3000 (e.g. change curl 'example.com' \...etc to curl '127.0.0.1:3000' \...etc
You should now get that request on standard output as a JSON object and it's in the format that express usually deals with. Yay! Now, pipe it into your clipboard (likely xclip -selection c on linux) or probably even better, redirect it to a file.
...
Step 2 - ?
Step 3 - Profit :)
I have deployed my backend in heroku and i got my endpoints and was tested from postman.Now when i updated my heroku endpoint in .env file of react js but still it doesnt work.what may be the issue behind it?
This is my .env file:
REACT_APP_BASE_URL ='http://payroll-account.herokuapp.com/api
This is my axios file and i am using .env file as following:
const BASE_URL = process.env.REACT_APP_BASE_URL || 'http://localhost:8080/api'
Now if i use as following in my axios file it works fine:
const BASE_URL = process.env.REACT_APP_BASE_URL || 'http://payroll-account.herokuapp.com/api'
Correct your REACT_APP_BASE_URL = 'http://payroll-account.herokuapp.com/api
You are adding a ' at the beginning of URL string. Please have a look that what is the different?
Anyway, now update your .env file:
REACT_APP_BASE_URL = http://payroll-account.herokuapp.com/api
And use it where you want something like below:
const BASE_URL = process.env.REACT_APP_BASE_URL || 'http://localhost:8080/api'
Hopefully now will work :)
I need to get number of items of specific directory in Node.js
If I get the items like
var dirItems = fs.readdirSync(__dirname+'/my_dir');
and then get specific item like
dirItems[1]
everything is ok
But if I try to get their number like
dirItems.length
or
Object.keys(dirItems).length
the page doesn't work in the browser
How to get the number of directory items?
UPDATED
My full code:
var http = require('http'),
fs = require('fs');
http.createServer(function(req, res) {
var dirItems = fs.readdirSync(__dirname+'/my_dir');
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(dirItems.length);
}).listen(80, 'localhost');
I was able to reproduce the error nyou get.
res.end() for the basic http server class is very picky about what you send it. You must give it a string (the error you got should have been a big clue here).
So, change this:
res.end(dirItems.length);
to this:
res.end(dirItems.length.toString());
And, it works for me. I was able to reproduce your original error and then make it work by making this simple change.
Logically, you can only send string data as an http response so apparently res.end() isn't smart enough to attempt a string conversion on its own. You have to do it yourself.
FYI, if you use a higher level framework like Express, it is more tolerant of what you send it (it will attempt a string conversion in a situation like this).
Here is how I would do it:
const fs = require('fs');
const dir = './somedir';
fs.readdir(dir, (err, files) => {
console.log(files.length);
});