Skip to content

Instantly share code, notes, and snippets.

@xgqfrms
Last active April 6, 2021 08:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xgqfrms/28436acbbc0b200b986ba263fa1176c1 to your computer and use it in GitHub Desktop.
Save xgqfrms/28436acbbc0b200b986ba263fa1176c1 to your computer and use it in GitHub Desktop.
Express.js Get HTTP POST json params
@xgqfrms
Copy link
Author

xgqfrms commented Apr 6, 2021

https://flaviocopes.com/express-post-query-variables/

Content-Type: application/json


fetch(`http://127.0.0.1:3000/api/post`, {
    body: JSON.stringify({key: "value"}),
    cache: "no-cache",
    headers: {
        "Content-Type": "application/json",
    },
    method: "POST", // *GET, POST, PUT, DELETE, etc.
    mode: "no-cors",
})
.then(res => console.log(`res =`, res))
.catch(err => console.error(`error =`, err));

@xgqfrms
Copy link
Author

xgqfrms commented Apr 6, 2021

@xgqfrms
Copy link
Author

xgqfrms commented Apr 6, 2021

image

mode: "no-cors", bug ❌

fetch(`http://127.0.0.1:3000/api/post`, {
    body: JSON.stringify({key: "value"}),
    cache: "no-cache",
    headers: {
        "Content-Type": "application/json",
    },
    method: "POST", // *GET, POST, PUT, DELETE, etc.
    mode: "no-cors",
})
.then(res => console.log(`res =`, res))
.catch(err => console.error(`error =`, err));

image

fetch(`http://127.0.0.1:3000/api/post`, {
    body: JSON.stringify({key: "value"}),
    cache: "no-cache",
    headers: {
        "Content-Type": "application/json",
    },
    method: "POST", // *GET, POST, PUT, DELETE, etc.
})
.then(res => console.log(`res =`, res))
.catch(err => console.error(`error =`, err));

image

@xgqfrms
Copy link
Author

xgqfrms commented Apr 6, 2021

@xgqfrms
Copy link
Author

xgqfrms commented Apr 6, 2021

https://developers.google.com/web/ilt/pwa/working-with-the-fetch-api

https://stackoverflow.com/questions/58007131/sec-fetch-mode-and-blocked-cors

image

whatwg/fetch#169

whatwg/fetch#9

express.js get post body bug

fetch(`http://127.0.0.1:3000/api/post`, {
    body: JSON.stringify({key: "value"}),
    cache: "no-cache",
    headers: {
        "Content-Type": "application/json",
    },
    method: "POST", 
     //  ❌,  can not read post body data
    mode: "no-cors",
})
.then(res => console.log(`res =`, res))
.catch(err => console.error(`error =`, err));
fetch(`http://127.0.0.1:3000/api/post`, {
    body: JSON.stringify({key: "value"}),
    cache: "no-cache",
    headers: {
        "Content-Type": "application/json",
    },
    method: "POST",
    // ✅ can read post body data
    // mode: "cors",
})
.then(res => console.log(`res =`, res))
.catch(err => console.error(`error =`, err));
fetch(`http://127.0.0.1:3000/api/post`, {
    body: JSON.stringify({key: "value"}),
    cache: "no-cache",
    headers: {
        "Content-Type": "application/json",
    },
    method: "POST",
    // ✅ can read post body data
    // mode: "no-cors",
})
.then(res => console.log(`res =`, res))
.catch(err => console.error(`error =`, err));

image

@xgqfrms
Copy link
Author

xgqfrms commented Apr 6, 2021

image

http://127.0.0.1:3000/api/get?q={%22username%22:%22xgqfrms%22,%22member_since%22:%222012-10-21T05:26:39.239Z%22,%22total_score%22:182160,%22avatar%22:%22https://secure.gravatar.com/avatar/e7b8d8946d71e52d2670e0def364997a.jpg%22}

JSON & Fecth POST & Express.js Server

fetch(`http://127.0.0.1:3000/api/post`, {
    body: JSON.stringify({key: "value"}),
    cache: "no-cache",
    headers: {
        "Content-Type": "application/json",
    },
    method: "POST",
    mode: "cors",
})
.then(res => {
   console.log(`res =`, res)
   return res.json()
})
// .then(res => res.json())
.then(json => console.log(`json =`, json))
.catch(err => console.error(`error =`, err));

// Promise {<pending>}
// res = Response {type: "basic", url: "http://127.0.0.1:3000/api/post", redirected: false, status: 200, ok: true, …}
// json = {res: "post api"}

image

@xgqfrms
Copy link
Author

xgqfrms commented Apr 6, 2021

https://developer.mozilla.org/zh-CN/docs/Web/API/Body/json

https://developers.google.com/web/updates/2015/03/introduction-to-fetch

https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch

// Example POST method implementation:

postData('http://example.com/answer', {answer: 42})
  .then(data => console.log(data)) // JSON from `response.json()` call
  .catch(error => console.error(error))

function postData(url, data) {
  // Default options are marked with *
  return fetch(url, {
    body: JSON.stringify(data), // must match 'Content-Type' header
    cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
    credentials: 'same-origin', // include, same-origin, *omit
    headers: {
      'user-agent': 'Mozilla/4.0 MDN Example',
      'content-type': 'application/json'
    },
    method: 'POST', // *GET, POST, PUT, DELETE, etc.
    mode: 'cors', // no-cors, cors, *same-origin
    redirect: 'follow', // manual, *follow, error
    referrer: 'no-referrer', // *client, no-referrer
  })
  .then(response => response.json()) // parses response to JSON
}

@xgqfrms
Copy link
Author

xgqfrms commented Apr 6, 2021

@xgqfrms
Copy link
Author

xgqfrms commented Apr 6, 2021

VM35:1 Refused to connect to 'http://127.0.0.1:3000/api/post' because it violates the following Content Security Policy directive: "default-src 'none'". Note that 'connect-src' was not explicitly set, so 'default-src' is used as a fallback.

image

http://127.0.0.1:3000/api/get?q={%22username%22:%22xgqfrms%22}

http://127.0.0.1:3000/api/get

@xgqfrms
Copy link
Author

xgqfrms commented Apr 6, 2021

@xgqfrms
Copy link
Author

xgqfrms commented Apr 6, 2021

express.js & Content-Security-Policy: connect-src

res.set("Content-Security-Policy", "default-src 'self'");

https://content-security-policy.com/examples/express-js/

app.use(function(req, res, next) {
    res.setHeader("Content-Security-Policy", "script-src 'self' https://apis.google.com");
    return next();
});

https://stackoverflow.com/questions/21048252/nodejs-where-exactly-can-i-put-the-content-security-policy

demo

app.use(function (req, res, next) {
  // JSON parse
  // console.log('req.body', req.body);
  // CORS bug
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  // res.header("Content-Security-Policy", "connect-src *");
  res.header("Content-Security-Policy", "connect-src '*'");
  // res.header("Content-Security-Policy", "connect-src localhost");
  // Content-Security-Policy: connect-src <source>;
  // Content-Security-Policy: connect-src <source> <source>;
  // res.header('Content-Type', 'application/json');
  // res.setHeader('Content-Type', 'application/json');
  next();
});

@xgqfrms
Copy link
Author

xgqfrms commented Apr 6, 2021

image

http://localhost:3000/api/get?q={%22username%22:%22xgqfrms%22}

fetch(`http://localhost:3000/api/post`, {
    body: JSON.stringify({key: "value"}),
    cache: "no-cache",
    headers: {
        "Content-Type": "application/json",
    },
    method: "POST",
    mode: "cors",
})
.then(res => {
   console.log(`res =`, res)
   return res.json()
})
// .then(res => res.json())
.then(json => console.log(`json =`, json))
.catch(err => console.error(`error =`, err));

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment