简体   繁体   中英

How do you use an api key in Node.js?

I am using both express and request, but when I try to enter the URI into the request, the console says ' Invalid URI "api.openweathermap.org/data/2.5/weather?q=Raleigh,NC,US&appid={apiKey}" '. It would be easier if I showed you my code:

const request = require('request'); 
const express = require('express');
const HTTP_PORT = process.env.HTTP_PORT || 3001;
const app = express();

let bodyContent = null;

request.get("api.openweathermap.org/data/2.5/weather?q=Raleigh,NC,US&appid={apiKey}", function(err, res, body) {
    if(!err && res.statusCode == 200) { // Successful response
        console.log(body); // Displays the response from the API
        bodyContent = body;
    } else {
        console.log(err);
        bodyContent = err;
    }
});

app.get("/weatherData", (req, res) => {
    res.jsonp(bodyContent);
});

app.listen(HTTP_PORT, () => console.log(`Listening on port ${HTTP_PORT}`));

Note: I have hidden my api key for security reasons. My actual code replaces {apiKey} with my actual api key.

The documentation for this api says that the "api.openweathermap.org/..." URI is the proper way to make an api call. However, whenever I try to use this, nothing works.

Here is a link to the website so that you can see what I mean:

https://openweathermap.org/current#call

Here is my proposition, I added .dotenv package, and changed the code a little for this case.

const request = require("request");
const express = require("express");
const HTTP_PORT = process.env.HTTP_PORT || 3001;
require("dotenv").config();
const app = express();

let bodyContent = null;

request.get(
  `${process.env.BASE_URL}weather?q=Raleigh,NC,US&appid=${process.env.API_KEY}`,
  function (err, res, body) {
    if (!err && res.statusCode == 200) {
      // Successful response
      console.log(body); // Displays the response from the API
      bodyContent = body;
    } else {
      console.log(err);
      bodyContent = err;
    }
  }
);

app.get("/weatherData", (req, res) => {
  res.jsonp(bodyContent);
});

app.listen(HTTP_PORT, () => {
  console.log(`Server is  listening at http://localhost:${HTTP_PORT}`);
});

in VSCode:

在此处输入图像描述


.env file: 在此处输入图像描述


browser: http://localhost:3001/weatherData 在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM