首页 > 解决方案 > node-fetch 将帖子正文作为表单数据发送

问题描述

我正在尝试发送带有正文的 POST 请求,form-data因为这似乎是唯一可行的方法。

我也在 Postman 中尝试过,但发送body失败raw JSON

所以我尝试做同样的事情,node-fetch但似乎body正在发送,JSON并且我收到与以前相同的错误(raw从 Postman 使用时)。

try{
  const { streamId } = request.body;
  const headers = {        
    "Authorization": INO_AUTHORIZATION_CODE,
    // "Content-Type": "multipart/form-data; boundary=<calculated when request is sent>"
    "Content-Type": "application/json"
  }      
  const url = `https://www.inoreader.com/reader/api/0/stream/contents/${streamId}`;
  const body = {
      AppId: INO_APP_ID,
      AppKey: INO_APP_KEY
  }
  
  const resp = await fetch(url, {
      method: 'POST',
      body: JSON.stringify(body),
    //   body: body,
      headers: headers
    });   
    
  const json = await resp.text();
  return response.send(json);
} catch(error) {
    next(error);
}

仅将正文设置为form-data有效:

在此处输入图像描述

标签: node.jspostpostmannode-fetch

解决方案


您需要使用他们的文档中提到的 form-data 包, 以便您的代码

const FormData = require('form-data');

const form = new FormData();
form.append('AppId', INO_APP_ID);
form.append('AppKey', INO_APP_KEY);

const resp = await fetch(url, {
      method: 'POST',
      body: form
    }); 

推荐阅读