Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

nodejs fetch

作者:携剑笑红尘   发布日期:2025-06-09   浏览:48

// 使用 Node.js 中的 fetch API 示例

// 首先需要安装 node-fetch 包,因为 Node.js 本身并不自带 fetch API
// 可以通过以下命令安装:
// npm install node-fetch

const fetch = require('node-fetch');

// 简单的 GET 请求示例
async function fetchData() {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/posts');
    const data = await response.json();
    console.log(data); // 打印从 API 获取的数据
  } catch (error) {
    console.error('请求出错:', error);
  }
}

fetchData();

// POST 请求示例
async function postData() {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/posts', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        title: 'foo',
        body: 'bar',
        userId: 1,
      }),
    });
    const data = await response.json();
    console.log(data); // 打印 POST 请求返回的数据
  } catch (error) {
    console.error('请求出错:', error);
  }
}

postData();

解释说明:

  1. 安装 node-fetch:Node.js 本身并没有内置 fetch API,因此我们需要通过 npm install node-fetch 来安装它。
  2. GET 请求:使用 fetch 发送一个简单的 GET 请求到指定的 URL,并将响应数据解析为 JSON 格式,然后打印出来。
  3. POST 请求:使用 fetch 发送一个 POST 请求,设置请求头和请求体(JSON 格式),并将服务器返回的数据解析为 JSON 格式后打印出来。

上一篇:js ...是什么意思

下一篇:js sleep函数

大家都在看

js 数组对象排序

js 数组删掉第一个值

js fill

js 数组复制

js 复制数组

js 数组拷贝

js 对象转数组

js 深拷贝数组

js 获取今天年月日

js jsonp

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站