Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
225 views
in Technique[技术] by (71.8m points)

javascript - managing CORS with fetch API GET request

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":"[email protected]",
   "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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...