JavaScript Day28 - HTTP 网路请求

网路请求

之前在 AJAX 时提到了不少用法,其实请求的方法有不少,传递的资料也有不同,如果前後端分离,两者其实就是用 API 沟通,因此做个纪录

  • 前面的笔记
  • method:请求的方法
    • GET:取得资料,参数或资料会直接在网址上,如取得一般资料
    • POST:提交(新增)资料,参数或资料不会在网址上,如建立订单资料
    • PATCH:修改部分资料,如修改订单资料
    • PUT:修改全部资料,如修改整笔订单资料
    • DELECT:删除资料,如删除订单资料
  • content-type:对於 post 主要有这几种传递资料的种类
    • application/x-www-form-urlencoded:一般的 form 表单送出的方式
    • application/json:主要是送出 JSON 格式的资料
    • multipart/form-data:当要传送档案的时候
    • text/plain:一般的文字

fetch

// post
const url = '';  // API url
const data = {
  "name": name.value,
  "password": password.value
}; // JSON data

fetch(url,{
  method:'POST', // 依需求更换 method
  body:JSON.stringify(data), // 依需求调整格式
  headers: {'Content-Type': 'application/json'}  // 依需求调整格式
  }).then() // function
// 假设有一个 form 的上传表单
let formData = new FormData();
let fileField = document.querySelector("input[type='file']");

formData.append('username', 'abc123');
formData.append('avatar', fileField.files[0]);

// fetch post
fetch('https://example.com/profile/avatar', {
  method: 'POST',
  body: formData
})
.then(response => response.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));

axios

let url = 'https://apiurl';
let data = {
    // JSON data
};

//请求表头
let headers = {
    "Content-Type": "application/json"
};

// post
axios({
    method: 'post',
    url: url,
    data: data,
    headers: headers
})

参考资料

MDN HTTP 请求方法
MDN Content-Type
MDN Using Fetch
[第四周] 网路基础 - HTTP、Request、Response
AJAX 完整解说系列:新增、更新、删除(POST/PATCH/DELETE)
JavaScript基本功修练:Day29 - axios基本语法与练习(GET、POST请求)
axios 基本使用 & Config
Fetch & Promise 笔记五(Fetch 的使用注意事项)
RESTful API 练习 (XHR, Fetch详解)
API 是什麽? RESTful API 又是什麽?

次回

做个此次系列的相关资料补充


<<:  【Day28】一些面试相关的题目

>>:  [Day28] 正规表达式 Regular Expression

【Day 26】Google Apps Script - API Blueprint 篇 - Apiary 介面介绍

Apiary 介面分4个区块:功能列区、编辑区、预览区、测试区。 今日要点: 》Apiary 介面...

CTF 初体验

今天来分享第一次打 CTF 的故事! 进入正题 在 3 天前的文章中已经提过我是如何入门网路安全的,...

D23 - 「不断线的侏罗纪」:有一只小恐龙在跑步

来建立我们的主角小恐龙吧。 建立组件 建立小恐龙组件 dino.vue src\components...

[Day32] Angular Material

虽然我们的网站终於整个都布署到云端上,而且功能都正常了,但是,我们的页面外观仍然是丑到不忍直视,虽然...

[DAY 14] Route 53

Rout 53 是 AWS 提供的 DNS service, 具有高可用性, 高扩展性 额外提一点...