0

is there any code that is similar to the code in the bottom but in a regular js and not in jquery? thank you!

$(function(){
$.ajax({
  url: 'http://localhost:28017/local/andyb',
  type: 'get',
  dataType: 'jsonp',
  jsonp: 'jsonp', // mongod is expecting the parameter name to be called "jsonp"
  success: function (data) {
    console.log('success', data);
  },
  error: function (XMLHttpRequest, textStatus, errorThrown) {
    console.log('error', errorThrown);
  }
});
  • Hi, Welcome to CO. Could you please re-arrange your sentences to make you clear? We don't understand what's the problem you meet and what you want to do. – Shawn Xiao May 14 '20 at 06:06
  • If you need JSONP, why not just load it as JSONP in a script tag? – mplungjan May 14 '20 at 06:11

1 Answers1

1

You can use fetch API, it's part Web APIs so if you want to use it with node you need to do special import.

async function postData(url = '', data = {}) {
  // Default options are marked with *
  const response = await fetch(url, {
    method: 'POST', // *GET, POST, PUT, DELETE, etc.
    mode: 'cors', // no-cors, *cors, same-origin
    cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
    credentials: 'same-origin', // include, *same-origin, omit
    headers: {
      'Content-Type': 'application/json'
      // 'Content-Type': 'application/x-www-form-urlencoded',
    },
    redirect: 'follow', // manual, *follow, error
    referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
    body: JSON.stringify(data) // body data type must match "Content-Type" header
  });
  return response.json(); // parses JSON response into native JavaScript objects
}

postData('https://example.com/answer', { answer: 42 })
  .then(data => {
    console.log(data); // JSON data parsed by `response.json()` call
  });

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API

Maciek
  • 88
  • 1
  • 10
  • Could you possibly tailor your answer to OP's code instead of just dumping a copypasta of [Using Fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch) – mplungjan May 14 '20 at 06:09
  • Yes, but I think that comments in the code are enough to author do it by himself and learn something, no just copy, paste ready answer. I've pasted the code to save his time going for external links. – Maciek May 14 '20 at 06:15