Inside Man
Inside Man

Reputation: 4293

Fetch HTTP Request and Navigate - Chrome

Here is a sample POST request which I run inside the Console window of Chrome.

fetch("https://demo.wpjobboard.net/wp-login.php", {
  "headers": {
    "Host": "demo.wpjobboard.net:443",
    "Content-Length": "19",
    "Cookie": "wpjb_transient_id=1607759726-1847; wordpress_test_cookie=WP+Cookie+check",
    "Content-Type": "application/x-www-form-urlencoded"
  },
  "body": "log=7887&pwd=789789",
  "method": "POST",
}).then(console.log);

I need to navigate and see HTML rendered results inside the chrome, not just seeing some complex results inside the console. How to achieve this?

Upvotes: 0

Views: 1693

Answers (1)

sultan
sultan

Reputation: 4739

Fetch returns promise and first what you get is streaming data from your server. You need to convert it to text or JSON after that you can use it like a normal variable.

I have moved your URL and options in separate variables in order to focus code on fetch request implementation.

const url = `https://demo.wpjobboard.net/wp-login.php`
const opts = {
  headers: {
    'Cookie': `wpjb_transient_id=1607759726-1847; wordpress_test_cookie=WP+Cookie+check`,
    'Content-Type': `application/x-www-form-urlencoded`
  },
  body: `log=7887&pwd=789789`,
  method: `POST`,
}

fetch(url, opts)
  .then(res => res.text()) // if you get json as response use: res.json()
  .then(html => {
    const win = window.open(``, `_blank`)
    win.document.body.innerHTML = html
    win.focus()
  })

Upvotes: 1

Related Questions