Why does .json() return a promise?

I’ve been messing around with the fetch() api recently, and noticed something which was a bit quirky. let url = “http://jsonplaceholder.typicode.com/posts/6”; let iterator = fetch(url); iterator .then(response => { return { data: response.json(), status: response.status } }) .then(post => document.write(post.data)); ; post.data returns a Promise object. http://jsbin.com/wofulo/2/edit?js,output However if it is written as: let url … Read more

What is an opaque response, and what purpose does it serve?

I tried to fetch the URL of an old website, and an error happened: Fetch API cannot load http://xyz. No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://abc’ is therefore not allowed access. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled. … Read more

Basic authentication with fetch?

I want to write a simple basic authentication with fetch, but I keep getting a 401 error. It would be awesome if someone tells me what’s wrong with the code: let base64 = require(‘base-64’); let url=”http://eu.httpbin.org/basic-auth/user/passwd”; let username=”user”; let password = ‘passwd’; let headers = new Headers(); //headers.append(‘Content-Type’, ‘text/json’); headers.append(‘Authorization’, ‘Basic’ + base64.encode(username + “:” … Read more

How do I POST a x-www-form-urlencoded request using Fetch?

I have some parameters that I want to POST form-encoded to my server: { ‘userName’: ‘[email protected]’, ‘password’: ‘Password!’, ‘grant_type’: ‘password’ } I’m sending my request (currently without parameters) like this var obj = { method: ‘POST’, headers: { ‘Content-Type’: ‘application/x-www-form-urlencoded; charset=UTF-8’, }, }; fetch(‘https://example.com/login’, obj) .then(function(res) { // Do stuff with result }); How can … Read more

How do I post form data with fetch api?

My code: fetch(“api/xxx”, { body: new FormData(document.getElementById(“form”)), headers: { “Content-Type”: “application/x-www-form-urlencoded”, // “Content-Type”: “multipart/form-data”, }, method: “post”, } I tried to post my form using fetch api, and the body it sends is like: —————————–114782935826962 Content-Disposition: form-data; name=”email” [email protected] —————————–114782935826962 Content-Disposition: form-data; name=”password” pw —————————–114782935826962– (I don’t know why the number in boundary is changed … Read more