I have a question about Fetch() API.

Asked 2 years ago, Updated 2 years ago, 75 views

In order to display JSON data from addresses with different domains in the ReactJS page component in the console window, I wrote the code as below.

const url = 'http://example.com/';

fetch(
    url, {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'Auth-Key': 'Lrmgdf...'
    },
    method: 'POST'
).then(
    response => response.json()
).then(
    data => console.log(data));

Chrome encountered a CORS error, but I thought it wouldn't matter if it was called on another domain, but Chrome actually shows the following error log.

Unhandled Rejection (TypeError): Failed to execute 'fetch' on 'Window': Invalid name

The caller is written in PHP and can only be accessed with Auth-Key, so I asked you this question because I couldn't find the right keyword even if I googled.

I would appreciate it if you could just tell me the API or method related to it.

reactjs fetch web javascript api

2022-09-22 12:24

1 Answers

Maybe you wrote the wrong factor for fetch()

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch contains both http header and method options in the second factor object.

e.g.

fetch(url, {
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
    'Auth-Key': 'Lrmgdf...'
  },
  method: 'POST'
})


2022-09-22 12:24

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.