A
A
Alexander2020-02-04 19:32:27
HTTP headers
Alexander, 2020-02-04 19:32:27

How to setup fetch and server to accept json from another site?

I'm trying to write a site parser myself, so that it then saves data somewhere. The problem came with saving. The site where the php handler is located is parsed and saved normally. But if you run the script from the console on another site, then the file is created, but the data does not get into it.
Googled a lot, but couldn't figure it out. What are the correct parameters in fetch and what should be done on the server or what should I write in .htacces? There I tried different options, now I have removed everything.

fetch(URL, {
    method: "POST",
    mode: "cors",
    credentials: "include",
    headers: {
        "Content-Type": "application/json"
    },
    body: JSON.stringify(json)
})


In the console gives:
Request from foreign source blocked: The single origin policy prohibits reading the remote resource at https://site.ru/parse/json.php . (Reason: missing CORS header "Access-Control-Allow-Origin").

Request from foreign source blocked: The single origin policy prohibits reading the remote resource at https://site.ru/parse/json.php . (Reason: CORS request failed).

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
GrayHorse, 2020-02-04
@GrayHorse

mode: "cors"
This is not a magic phrase that disables CORS. This fetch request mode is only needed for the service worker to cache resources that can be "cross-origin embed" and nothing else.
You also need the server to return the header Access-Control-Allow-Origin: https://yoursite.com, where https://yoursite.comis the site on which the script is running. It is possible *instead https://yoursite.comof , if fetch will be without credentials: "include".

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question