NodeJS 18 Fetch API

2025-05-25

NodeJS 18 Fetch API

NodeJS 18 引入了一些很酷的新功能,其中最实用的就是内置的 Fetch API。这意味着我们不再需要使用第三方 npm 包,node-fetch因为这些功能现在是 Node 原生的,并且内置在 Node 中。这样一来,我们需要安装的依赖项就少了一个,node_modules文件夹也变得更轻量了。

在使用最新的 NodeJS 功能(例如 Fetch API)之前,您需要先检查计算机上运行的 Node 版本是否为最新版本。node -v在控制台中运行以下命令查看当前运行的 Node 版本。如果版本低于 18,则需要升级才能使用这些新功能。

使用 Fetch API

如果您已经熟悉在开发 JavaScript 应用时在浏览器中使用 Fetch API,那么此语法应该很容易理解。我们终于有了一个使用 JavaScript 在后端获取数据的原生解决方案。

const getAPI = async () => {
    const res = await fetch('https://pokeapi.co/api/v2/pokemon/');

    if (res.ok) {
        const data = await res.json();

        console.log(data);
    }
};

getAPI();
Enter fullscreen mode Exit fullscreen mode

让我们创建一个实际示例,以便您了解一个潜在的用例。导航到一个目录,然后将下面的代码复制并粘贴到命令行中,以搭建一个项目。

mkdir node-backend-fetch
cd node-backend-fetch
npm init -y
npm i express nodemon
touch app.js
mkdir controllers routes
touch controllers/pokemon.js
touch routes/pokemon.js
Enter fullscreen mode Exit fullscreen mode

在代码编辑器中打开项目,然后将下面的代码复制到相应的文件中。

controllers/pokemon.js

exports.getPokemon = async (req, res) => {
    const api = await fetch('https://pokeapi.co/api/v2/pokemon/');

    if (api.ok) {
        const data = await api.json();

        console.log(data);

        try {
            res.json(data);
        } catch (error) {
            console.log(error);
        }
    }
};

exports.getPokemonMoves = async (req, res) => {
    const api = await fetch('https://pokeapi.co/api/v2/move/');

    if (api.ok) {
        const data = await api.json();

        console.log(data);

        try {
            res.json(data);
        } catch (error) {
            console.log(error);
        }
    }
};
Enter fullscreen mode Exit fullscreen mode

routes/pokemon.js

const express = require('express');

const pokemonController = require('../controllers/pokemon');

const router = express.Router();

router.get('/pokemon', pokemonController.getPokemon);

router.get('/pokemon-moves', pokemonController.getPokemonMoves);

module.exports = router;
Enter fullscreen mode Exit fullscreen mode

app.js

const express = require('express');

const pokemonRoute = require('./routes/pokemon');

const app = express();

app.use('/', pokemonRoute);

const port = process.env.PORT || 3000;

app.listen(port, () => console.log(`Server running on ${port}, http://localhost:${port}`));
Enter fullscreen mode Exit fullscreen mode

package.json

添加这些运行脚本。

"scripts": {

"start": "node app.js",

"dev": "nodemon app.js"

},
Enter fullscreen mode Exit fullscreen mode

仔细检查以确保您正在使用 Node 18,然后运行命令npm run dev来启动后端服务器。

如果你访问http://localhost:3000/pokemon,你应该会得到一个以 JSON 格式返回的 Pokemon 列表。数据也会被记录到控制台中。

如果你访问http://localhost:3000/pokemon-moves,你应该会得到一个 Pokemon 招式列表,它也以 JSON 格式返回。与另一个示例一样,数据也会记录到控制台中。

最后的想法

以上是对 NodeJS 18 Fetch API 使用的简要介绍。更多信息请查看官方公告

文章来源:https://dev.to/andrewbaisden/the-nodejs-18-fetch-api-72m
PREV
如何进行精彩绝伦的科技演讲。附技巧🛠
NEXT
2022 年现代 React 开发者全书