-1

i apparently try to fetch data from local nodejs server but got weird error. this is simple server with express

let express = require('express')
let server = express()
server.listen(3100)
server.get("/", (req, res) => {
res.send("hello") })

and this is the code in my react. i only use it in useEffect

fetch('http://localhost:3100/', {
        headers: 'Access-Control-Allow-Origin',
        method: "GET"
    })
        .then(res => res.json())
        .then(response => {
            console.log(response)
        })
        .catch(err => console.log(err))

and i got this error

Uncaught (in promise) TypeError: Failed to execute 'fetch' on 'Window': The provided value is not of type '(sequence<sequence<ByteString>> or record<ByteString, ByteString>)'

i have no idea why is this happening, i look around the internet but still didnt get the solution. thanks for any suggestion!

  • `headers` is an object and moreover `Access-Control-Allow-Origin` should done by the `server` side. `headers: { 'Content-type': 'application/json', etc...}` – Naren Feb 24 '21 at 09:37
  • This is a strange error indeed but sometimes node debugging is messy and the errors seem irrelevant. A relevant error might be with cross-origin, as I am assuming you run your 'fetch' app on a different local port and need cors enabled. You need to add server.use(cors()); to your node app to enable cross-origin requests – Stavros Angelis Feb 24 '21 at 09:39
  • @StavrosAngelis — It's a browser side error, nothing to do with Node. – Quentin Feb 24 '21 at 09:41
  • True but if the server API doesn't allow cross-origin requests the 'fetch' request will also fail so that also needs fixing. – Stavros Angelis Feb 24 '21 at 09:48

2 Answers2

1

The error is because the value of headers cannot be a string.

It should be a plain object (or a Headers instance) where each property is a header name and the associated value is the header value. (Source)

headers: {
    "X-Example-Request-Header": "Example value"
}

In this particular case, you shouldn't be setting headers at all. Access-Control-Allow-Origin is a response header, not a request header. Adding it to the request can only cause problems.

See this question for further reading on that subject and the cors middleware to add CORS permissions to your Express server.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
-1

You need to add a header that is not of type string, it should be of type Header

fetch(' URL ... ',
{
method: "GET",
    headers: new Headers({
        Accept: 'application/json',
        'Content-Type': 'multipart/form-data'
    }),
    body: formData
}
Elias Fizesan
  • 265
  • 1
  • 3
  • 18