Calling External API with Javascript

前端 未结 5 1810
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-14 03:33

I need to make a POST request to an external server from my webpage using Javascript. The body and response are both json. I can\'t figure out how to make this call or what tool

5条回答
  •  抹茶落季
    2021-02-14 04:18

    You are violating the so called same-origin-policy here. Most browsers don't allow a script to access URLs that do not have the same hostname and port than the page where the script is located. This is a very strict security policy and has often been very difficult to overcome even for testing purposes.

    Traditionally the easiest way to go around this has been to use your own web site as a proxy and forward the request through it to the external server. But if you don't have enough control on your own site to implement such a solution, things have been more complicated. If you search the Internet with "same-origin-policy", you'll find a lot of discussion on the topic and other ideas to solve it.

    My first suggestion would be to check the "Access-Control-Allow-Origin" that your error message mentions, though I'm not familiar with it myself. It is related to a new scheme called CORS that has been added to W3C recommendations quite recently (2014), and seems to have a wide support in the newest versions of many browsers. Maybe we developers are finally getting some tools to work with this irritating issue.

提交回复
热议问题