// Make sure you run it from the domain 'https://jsonplaceholder.typicode.com/'. (cross-origin-policy)fetch('https://jsonplaceholder.typicode.com/posts',{method: 'POST', headers: {'test': 'TestPost'} }).then(response => response.json()).then(json => console.log(json))
// Example POST method implementation:async function postData(url = '', data = {}, options = {}) {// Default options are marked with *let defaultOptions = {method: 'POST', // *GET, POST, PUT, DELETE, etc.mode: 'cors', // no-cors, *cors, same-origincache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cachedcredentials: 'same-origin', // include, *same-origin, omitheaders: {'Content-Type': 'application/json'// 'Content-Type': 'application/x-www-form-urlencoded',},redirect: 'follow', // manual, *follow, errorreferrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-urlbody: JSON.stringify(data) // body data type must match "Content-Type" header}
// update the default options with specific options (e.g. { "method": "GET" } )const requestParams = Object.assign(defaultOptions, options);
const response = await fetch(url, requestParams);return response.text(); // displays the simplest form of the output in the console. Maybe changed to response.json() if you wish}
如果您想提出请求,您可以将它们放在浏览器地址栏中!
如果将其粘贴到控制台中,则可以通过重复调用函数来发出POST请求,如下所示:
postData('https://example.com/answer', { answer: 42 }).then(data => {console.log(data); // you might want to use JSON.parse on this});