managing CORS with fetch API GET request

2019-09-24 09:55发布

问题:

I have an end point at localhost:8080/enquiry

which renders the following JSON:

[{"_id":"5a283e4c5a36f4556af34742",
   "firstName":"bob",
   "surname":"hoskins",
   "telephoneNumber":939483948,
   "gender":"male",
   "dayOfBirth":17,
   "monthOfBirth":5,
   "yearOfBirth":1978,"comments":"hello",
   "emailAddress":"jimmsrrs@gmail.com",
   "createdAt":"2017-12-06T19:00:28.401Z"}]

I have an action creator that looks like this

export const receiveEnquiries = enquiries => ({
    type: RECEIVE_ENQUIRIES,
    enquiries 

  });
export const fetchEnquiries = () => dispatch => (
    enquiryAPIUtil
        .fetchEnquiries() // this is the fetch call in api.js below
        .then((enquiries) => {dispatch(receiveEnquiries(enquiries))})
    );

I have a fetch request that looks like this in api.js :

export const fetchEnquiries = () =>
    fetch(`${api}/enquiry`, { headers })
    .then(res => {
        res.json()
        console.log("res",res)
    })
    .then(data => console.log("data",data))

In the console instead of logging the JSON above it logs the following:

res Response {type: "cors", url: "http://localhost:8080/enquiry", 
redirected: false, status: 200, ok: true, …} 

In the express server.js I have

 const cors = require('cors')
 app.use(cors())

(As well as the code that renders the JSON)

Im wondering if it is more likely that I am doing something wrong on the client side of server side?

回答1:

res.json() returns a promise of an object parsed from JSON.

You ignore its returned object, so you don't get any JSON.