user12551065
user12551065

Reputation:

Data is not rendering / console.log using axios , using data from mongoDB

My request to the endpoint: http://localhost:3200/api/posts/ returns an array of objects using POSTMAN, these object have values of title, description and image.

enter image description here

on my front end I have made a component that attempts to extract these values using axios and useEffect from react , then to render them.

const Posts = () => {

  let [posts, setPosts] = useState([])
  console.log(posts)

      useEffect(() => {
        axios.get("http://localhost:3200/api/posts/")
            .then(({ data })=> {
       console.log('data====',data);
              setPosts(
         data
       );
     })
            .catch(err => {
              console.log(err);
            })
    }, []);

  return (
    <ul>
            {posts.map((item, index) => <li key={index}>{item.title}</li>)}
    </ul>
  );




}

I am rendering the component of Posts below the form where I am getting the data, the Title is showing but the componet does not load any data.. ![enter image description here

return (
    <>
    <form onSubmit={submitFormHandle}>
          <div className="form-group">
             <ToastContainer />
      </div>

     <label htmlFor="formGroupExampleInput">Title</label>
     <input type="text" className="form-control" id="formGroupExampleInput" placeholder="Example input" onChange={onChangeTitle}/>


    <div className="form-group">
      <label htmlFor="comment">description</label>
      <textarea className="form-control" rows="5" id="comment" onChange={onChangeDescription}></textarea>
          </div>

          <div className="form-group files">

        <label htmlFor="exampleFormControlFile1">Upload Cat Memes</label>
        <input
          type="file"
          className="form-control"
          id="exampleFormControlFile1"
          multiple
          onChange={onChangeFile}
        />
          </div>

        <button type="submit" className="btn btn-primary">
            Submit
        </button>

    </form>

      <h3>View your posts</h3>
      <Posts />
  </>
  );
};

I get this error:

Error: Network Error at createError (createError.js:17) at XMLHttpRequest.handleError (xhr.js:80)

Upvotes: 1

Views: 92

Answers (1)

warmachine
warmachine

Reputation: 376

Allow cors in your backend and set headers like this.

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept"
  );
  next();
});

Upvotes: 1

Related Questions