How do I send a cross-domain POST request via JavaScript?

后端 未结 17 2386
说谎
说谎 2020-11-21 05:06

How do I send a cross-domain POST request via JavaScript?

Notes - it shouldn\'t refresh the page, and I need to grab and parse the response afterwards.

17条回答
  •  梦如初夏
    2020-11-21 06:05

    CORS is for you. CORS is "Cross Origin Resource Sharing", is a way to send cross domain request.Now the XMLHttpRequest2 and Fetch API both support CORS, and it can send both POST and GET request

    But it has its limits.Server need to specific claim the Access-Control-Allow-Origin, and it can not be set to '*'.

    And if you want any origin can send request to you, you need JSONP (also need to set Access-Control-Allow-Origin, but can be '*')

    For lots of request way if you don't know how to choice, I think you need a full functional component to do that.Let me introduce a simple component https://github.com/Joker-Jelly/catta


    If you are using modern browser (> IE9, Chrome, FF, Edge, etc.), Very Recommend you to use a simple but beauty component https://github.com/Joker-Jelly/catta.It have no dependence, Less than 3KB, and it support Fetch, AJAX and JSONP with same deadly sample syntax and options.

    catta('./data/simple.json').then(function (res) {
      console.log(res);
    });
    

    It also it support all the way to import to your project, like ES6 module, CommonJS and even

提交回复
热议问题