简体   繁体   English

发出 GET 和 POST 请求的正确方法

[英]Correct way to make GET and POST requests

I want to be able to write a review and display all written reviews (which is none at the moment since the page isn't built yet).我希望能够撰写评论并显示所有书面评论(目前还没有评论,因为页面尚未构建)。 It's my first time doing a project like this and I can't get it to work.这是我第一次做这样的项目,我无法让它工作。

App.js .应用程序.js I want const fetchReviews to GET and display all reviews that has been written and I want const postReview to simply post a new review to the page.我希望const fetchReviews获取并显示所有已撰写的评论,并且我希望const postReview简单地将新评论发布到页面。

import React, {useState, useEffect} from "react";

import { NewReview } from "./NewReview.js";
import { AllReviews } from "./AllReviews";

const reviewsURL = "http://localhost:8080/reviews"

export const App = () => {
  const [existingReviews, setExistingReviews] = useState([])
  const [newReview, setNewReview] = useState('')

  const fetchReviews = () => {
    fetch(reviewsURL)
    .then(response => response.json())
    .then((json) => {
      setExistingReviews(reviews)
    }).catch(error => {
      console.log(error.message)
    })
  }

  useEffect(() => {
    fetchReviews();
  }, []);


  const postReview = (event) => {
    event.preventDefault();

    fetch(reviewsURL, {
      method: 'POST',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify({message: newReview})
    })
    .then (response => response.json())
    .then (() => {
      fetchReviews();
      setNewReview('')
    }).catch(error => {
      console.log(error.message)
    })
  }
  return (
    <>

<NewReview
      newReview={newReview}
      setNewReview={setNewReview}
      handlesubmit={postReview}
      />

{<AllReviews 
        allReviews={existingReviews} 
        />}
    </>
  )
}

Index.js will act as my server, I'm using localhost. Index.js将充当我的服务器,我使用的是 localhost。 I will not use mongo/mongoose.我不会使用 mongo/mongoose。

I have tried many different things now for the past two weeks, read a bunch of questions and answers on Stack, I've tried import(), require(), update json package but I am so stuck.在过去的两周里,我尝试了很多不同的事情,阅读了一堆关于 Stack 的问题和答案,我尝试了 import()、require()、更新 json package,但我被困住了。 Which makes me wonder if the import and usage of AllReviews and NewReviews is even close to being correct?这让我想知道AllReviewsNewReviews的导入和使用是否接近正确?

Please help, I have spent so many hours on this.请帮忙,我在这上面花了很多时间。

import express from 'express'

import { NewReview } from '../frontend/src/NewReview.js';
import { AllReviews } from '../frontend/src/AllReviews.js';

const PORT = process.env.PORT || 8080;
const app = express();

app.get("/", (request, response) => {
    response.json({ message: "Hello from server!" });
  });

// GET all reviews
app.get("/reviews", (request, response) => {
  response.status(201).json(AllReviews)
});

  //POST a new review
  app.post('/reviews', async (request, response) => {
    try {
      response.status(201).json(NewReview)
    } 
      catch (err) {
      response.status(400).json({ message: 'Sorry, could not save review to the database', errors: err.errors
      })
    }
  })



app.listen(PORT, () => {
  console.log(`Server listening on http://localhost:${PORT}`);
});

NewReview.js新评论.js

import React from "react";

export const NewReview = ({newReview, setNewReview, handleSubmit}) => {
    return(
        <section className="newReviewContainer">
            <form onSubmit={handleSubmit}>
                <label>
                    <textarea
                    placeholder="Write your review here"
                    rows="3"
                    onChange={event => setNewReview(event.target.value)}
                    value={newReview}>
                    </textarea>
                </label>

                <button className="sendReview"
                type="submit">
                    <p>SEND REVIEW</p>
                </button>
            </form>
        </section>
    )
}

WebbH commented that I don't need to import my frontend files into my server. WebbH评论说我不需要将前端文件导入我的服务器。 So I deleted the part in my server where I tried to import it and that solved my problem.因此,我删除了服务器中尝试导入它的部分,这解决了我的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM