Node.js 中使用fetch 按JSON格式发post请求

最近在测试一个api,可以用curl命令直接访问,指定header相关配置,request body(JSON),成功后返回一个JSON。

原本想搞个静态页面html,在script标签里用fetch做个简单的demo的,结果就遇到跨域问题。遂使用后端请求,就想到了Nodejs。

既然有现成的工具,那就使用呗。

环境node --version: 18.15.0

1.全局安装express-generator:

npm i express-generator -g

2.生成一个测试项目:

express nodepost

3. 安装依赖

cd nodepost
npm install

4.试运行(没有意外的话可以在浏览器输入 localhost:3000,看到Express 欢迎页)

npm start

5. VSCODE编辑

code .

6.修改routers/index.js, 增加以下代码段,注意按你实际配置来(url, requestData, authkey...)

router.get('/json', (req, res, next) => {
  let success = true;
  const data = {
    k: 'your real data'
  };
  fetch('https://example.com/api/g', {
    method: 'POST',
    body: JSON.stringify(data),
    headers: {
      'Content-type': 'application/json; charset=UTF-8',
      'Authorization': 'your real auth key if neccessory, otherwise you could not config this item',

    },
  }
  ).then((res) => res.json())
  .then((json) => console.log(json))
  .catch(err => {
    success = false;
    console.log('err:', err);
  })
  res.json({
    success
  })
});

7.访问 localhost:3000/json, 不出问题的话能在后端控制台查看请求结果

PLUS:

选择新版本的Node,不能低于17.5.0,否则不能直接使用fecth,这blog面有说明。

低版本用node-fetch库或者原生的http模块, node-fetch我自己导入一直有问题,原生http模块要写不少东西,故不采用。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值