Node.js请求百度天气API并将其封装成接口供前端调用

nodejs yekong 326℃

要使用Node.js请求百度天气API并将其封装成接口供前端调用,你可以按照以下步骤进行操作:

  1. 首先,确保你已经安装了Node.js。如果没有安装,你可以在官方网站上下载并安装Node.js:nodejs

  2. 创建一个新的Node.js项目文件夹,并在该文件夹中初始化一个新的npm项目。你可以使用以下命令:

mkdir weather-api
cd weather-api
npm init -y
  1. 在项目文件夹中安装Express.js,这是一个常用的Node.js框架,用于创建Web服务器和API。使用以下命令安装Express.js:
npm install express --save
  1. 创建一个名为app.js的Node.js应用程序文件。这是你的应用程序的主要入口点。在app.js中,你可以编写以下代码:
const express = require('express');
const axios = require('axios');

const app = express();
const port = process.env.PORT || 3000;

const baiduWeatherApiUrl = 'https://api.map.baidu.com/weather/v1/?district_id=131125&data_type=all&ak=your ak';

// 创建一个GET路由,用于获取天气数据
app.get('/weather', async (req, res) => {
  try {
    const response = await axios.get(baiduWeatherApiUrl);
    const weatherData = response.data;
    res.json(weatherData);
  } catch (error) {
    console.error('Error fetching weather data:', error);
    res.status(500).json({ error: 'An error occurred while fetching weather data.' });
  }
});

app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

在上述代码中,我们创建了一个Express.js应用程序,设置了一个GET路由 /weather 用于获取天气数据。我们使用Axios库来发出HTTP GET请求以获取百度天气API的数据。

  1. 在项目文件夹中创建一个.env文件,用于存储敏感信息,例如API密钥。在.env文件中添加以下内容:
BAIDU_API_KEY=ak
  1. 安装dotenv库,以便在应用程序中读取.env文件中的环境变量。使用以下命令安装dotenv
npm install dotenv --save
  1. app.js 中添加以下代码来加载.env文件中的环境变量:
require('dotenv').config();
  1. 最后,启动你的Node.js应用程序:
node app.js

你的Node.js服务器将在端口3000上运行。现在,你可以从前端通过访问http://localhost:3000/weather来获取百度天气API的数据。

这样我们就可以获取到天气信息了。

Node.js请求百度天气API并将其封装成接口供前端调用

解决跨域

上面的代码默认是不允许跨域的,所以我们还需要解决一下跨域问题。

要设置Express.js应用程序以允许跨域请求,你可以使用CORS(跨源资源共享)中间件。以下是如何在你的Express.js应用程序中设置CORS:

  1. 首先,安装cors中间件:
npm install cors --save
  1. 在你的app.js 中导入cors
const express = require('express');
const axios = require('axios');
const cors = require('cors'); // 导入cors中间件

const app = express();
const port = process.env.PORT || 3000;

const baiduWeatherApiUrl = 'https://api.map.baidu.com/weather/v1/?district_id=131125&data_type=all&ak=your key';

// 使用cors中间件允许跨域请求
app.use(cors());

// 创建一个GET路由,用于获取天气数据
app.get('/weather', async (req, res) => {
  try {
    const response = await axios.get(baiduWeatherApiUrl);
    const weatherData = response.data;
    res.json(weatherData);
  } catch (error) {
    console.error('Error fetching weather data:', error);
    res.status(500).json({ error: 'An error occurred while fetching weather data.' });
  }
});

app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

上述代码中,我们导入了cors中间件并在Express应用程序中使用它。这会允许来自任何来源的跨域请求访问你的API。你还可以配置cors()函数来更精细地控制允许的来源、HTTP方法等。

前端请求

前端请求天气接口

getWeather() {
  axios.get('http://localhost:3000/weather')
      .then(function (response) {
        // 处理成功响应的数据
        console.log('天气数据:', response.data);
        // 在这里处理你的天气数据,更新UI等操作
      })
      .catch(function (error) {
        // 处理错误情况
        console.error('获取天气数据失败:', error);
        // 在这里处理错误,显示错误信息等操作
      });
},

前端请求天气接口

接受传值

district_id通过前端get传值,ak通过.env文件读取。

.env

.env文件

BAIDU_API_KEY=your ak

实例代码

const express = require('express');
const axios = require('axios');
const cors = require('cors');
require('dotenv').config();
const app = express();
const port = process.env.PORT || 3000;

const baseBaiduWeatherApiUrl = `https://api.map.baidu.com/weather/v1/?data_type=all&ak=${process.env.BAIDU_API_KEY}`;

app.use(cors());

app.get('/weather', async (req, res) => {
    const district_id = req.query.district_id;
    if (!district_id) {
        return res.status(400).json({ error: 'district_id is required.' });
    }

    const baiduWeatherApiUrl = `${baseBaiduWeatherApiUrl}&district_id=${district_id}`;

    try {
        const response = await axios.get(baiduWeatherApiUrl);
        const weatherData = response.data;
        res.json(weatherData);
    } catch (error) {
        console.error('Error fetching weather data:', error);
        res.status(500).json({ error: 'An error occurred while fetching weather data.' });
    }
});

app.listen(port, () => {
    console.log(`Server is running on port ${port}`);
});

喜欢 (0)