Help us understand the problem. What is going on with this article?

fetch API でも POST したい!

More than 3 years have passed since last update.

fetch API でも POST したい!

ちなみに fetch API は WHATWG HTML Living Standard で定義されていて、W3C HTML 5.1 でもなければ ECMAScript2017 でもないです。

2017年現在 Safari や IE では未サポートなので https://github.com/github/fetch などの polyfill を使うと良いです。

post (application/x-www-form-urlencoded)

const obj = {hello: "world"};
const method = "POST";
const body = Object.keys(obj).map((key)=>key+"="+encodeURIComponent(obj[key])).join("&");
const headers = {
  'Accept': 'application/json',
  'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
};
fetch("./new", {method, headers, body}).then((res)=> res.json()).then(console.log).catch(console.error);

post (multipart/form-data)

const obj = {hello: "world"};
const method = "POST";
const body = Object.keys(obj).reduce((o,key)=>(o.set(key, obj[key]), o), new FormData());
const headers = {
  'Accept': 'application/json'
};
fetch("./new", {method, headers, body}).then((res)=> res.json()).then(console.log).catch(console.error);

post (aplication/json)

const obj = {hello: "world"};
const method = "POST";
const body = JSON.stringify(obj);
const headers = {
  'Accept': 'application/json',
  'Content-Type': 'application/json'
};
fetch("./new", {method, headers, body}).then((res)=> res.json()).then(console.log).catch(console.error);
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした