我的服務器端檔案,這是server.js檔案 這是我為我的后端檔案要求的包
。
require("dotenv"/span>).config()。
const express = require("express")。
const mongoose = require("mongoose") 。
// const cors = require("cors");
const path = require("path") 。
const app = express()。
這是我處理mongodb的地方
// const PORT = process.env.PORT || 4000;/span> const DB_URI = "mongodb://localhost:27017/"/span> const DB = "reactDB"/span>。 // Middleware app.use(express.json()。 app.use(express.urlencoded({ extended。true })。 //app.use(cors()); //建立DB連接 mongoose.connect(DB_URI DB, { useUnifiedTopology: true, useNewUrlParser: true, useCreateIndex: true, useFindAndModify: false, connectTimeoutMS: 10000。 }); const db = mongoose.connection; //事件監聽器 db.once('open', () => console. log(`Connected to ${DB} database`)。 //創建模式。 let PersonSchema = new mongoose.Schema( { forename: String, 年齡。數字。 }, { collection: "people" }; { collection: "people" } ); //創建模型 let PersonModel = db.model("PersonModel", PersonSchema) 。 //獲取所有人員的路線。因為,錯誤是獲取后的請求錯誤,它可能是一些 這里也是如此。app. get("/api/people", (req, res) => /span> { PersonModel.find({}, {__v。0}, (err, docs) => { if (! err) { res.json(docs)。 } else { res.status(400).json({"error"/span>: err}) 。 } }); })我不能讓這個帖子請求得到處理。我不知道為什么?
// Route to Add a Person app.post("/api/person/add", (req, res) => /span> { let person = new PersonModel(req.body)。 person.save((err, result) =>/span> { if (! err) { // console.log("The result._doc.__v is " result._doc.__v); delete result._doc.__v。 res.json(result._doc)。 // console.log("The result._doc is" result._doc); } else { res.status(400).json({"error"/span>: err}) 。 } }); }) app.listen(4000, ( ) => { console.log(app.get("env"/span>)。 toUpperCase() " Server started on port " )。 });import React, { useState, useEffect } from "react"。 import Person from "./Person" ; import axios from "axios"/span>; /**** 記住,到后端服務器的代理是 http://localhost:4747 ***/ const defaultPerson = { forename。"", 年齡。""。 }; function App() { const [person, setPerson] = useState(defaultPerson)。 const [people, setPeople] = useState([] ); /* 當這個App組件第一次加載時,獲取所有的人。 注意。代理使我們能夠使用axios而不需要完整的urlhttp://localhost:4747/api/people。 空陣列[]引數確保useEffect()里面的代碼只運行一次。 */ useEffect(() => { axios.get("/api/people"/span>) .then((res) => setPeople(res.data) .catch((err) => console.error(err) )。 }, []); function handleChange(event) { const { name, value } = event.target; setPerson({ ...person, [name]: value }) 。 } /* 向DB添加一個人并更新狀態 注釋。代理使我們能夠使用axios而不需要完整的urlhttp://localhost:4747/api/person/add。 */ function addPerson(newPerson) { axios.post("/api/person/add"/span>, newPerson) .then((res) => setPeople([. .people, res.data] )) .catch((err) => console.log(err) )。 } return ( <>/span> <form onSubmit={(e) => e.preventDefault()}> <input。 name="forename"。 type="text"/span> placeholder="Enter your Forename" value={person.forename}> onChange={handleChange}。 /> <input name="age"。 type="text"/span> placeholder="Age"/span> value={person.age} onChange={handleChange}。 /> <button onClick={() => { if (person.forename && person.age) { addPerson(person); setPerson(defaultPerson)。 } }} > 添加 </button> {people.map((person) => ( <Person key ={person._id} _id ={person._id} forename={person.forename}。 年齡={person.age}。 /> ))} </form>)。 </> ); } export default App;uj5u.com熱心網友回復:
你正在監聽埠4000。要么把它改成3000埠,要么在你的URL中使用:4000.
。CodePudding
你沒有告訴你的react應用在哪里進行端點呼叫--所以它在使用自己作為參考。這就是為什么,當你在3000埠啟動React應用時,axios會對localhost:3000進行所有呼叫。如果你使用Create React App,一個解決方案是在你的
package.json中添加以下一行。"proxy": "http://localhost:4000"。否則,你將需要把整個資料交給axios,比如axios.get(http://localhost:4000/api/people;或者尋找不同的方式來代理你的應用程式和服務器。轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/319852.html
標籤:
