【问题标题】:Object properties not displaying on server对象属性未显示在服务器上
【发布时间】:2021-06-02 09:09:59
【问题描述】:

我正在关注 MERN 堆栈上的 this tutorial,因为我想看看所有部分如何组合在一起以更好地理解它。我的问题是,当我去加载在客户端输入的服务器对象属性(studentNameregNo)时,没有出现,除了默认值。当我转到http://localhost:5000/students/ 时,我看到以下内容:

在服务器端,我有以下内容:

/server/models/student.js 包含

import mongoose from 'mongoose';

const studentSchema= mongoose.Schema({
    regNo: Number,
    studentName: String,
    grade:  {
        type: String, default: 'hello'
    },
    section: {
        type: String, default: 'Z'
    }

})

const student = mongoose.model('student', studentSchema);
export default student;

/server/controllers/student.js 包含:

import StudentData from '../models/student.js';

export const getStudents = async (req, res)=>{
    try {
        console.log("This try statement worked")
        const allStudents= await StudentData.find(); //Goes to model and finds student data if available
        res.status(200).json(allStudents);
    } catch (error) {
        res.status(404).json({message: error.message});
        
    }
};

export const createStudent= async (req, res) =>{
    const student= req.body;

    const newStudent= new StudentData(student); //model(variable)

    try {
        await newStudent.save();
        res.status(201).json(newStudent);
    } catch (error) {
        res.status(409).json({message: error.message})
        
    }
}

/server/routes/students.js 包含

import express from "express";
import { getStudents, createStudent} from "../controllers/student.js"
import student from '../models/student.js';
const router = express.Router();
router.get("/", getStudents); //res = response req=request
router.post("/", createStudent); 
export default router;

在客户端我有/client/components/createStudent/createStudent.js:

import React, {useState} from 'react';
import { makeStyles } from '@material-ui/core/styles';
import TextField from '@material-ui/core/TextField';
import Button from '@material-ui/core/Button';
import axios from 'axios';

const useStyles = makeStyles((theme) => ({
  root: {
    '& > *': {
      margin: theme.spacing(1),
      width: '25ch',
    },
  },
}));



export default function Create() {
  const classes = useStyles();
  const [student, setStudent]= useState({
    regNo: 0,
    studentName: '',
    grade: '',
    section: ''
  }); //React hook. Updates data in text fields on frontend
  const createStudent = () => {
  axios.post("http://localhost:5000/students", student)


} 
  return (
    <>
    <h2>Create Student</h2>
    <form className={classes.root} noValidate autoComplete="off">
      <TextField id="outlined-basic" label="Registration No." variant="outlined" value={student.regNo} onChange={(event) =>{
        setStudent({...student, regNo: event.target.value})
      }}  />
      <TextField id="outlined-basic" label="Name" variant="outlined" value={student.studentName} onChange={(event) =>{
        setStudent({...student, studentName: event.target.value})
      }} /><TextField id="outlined-basic" label="Grade" variant="outlined" value={student.grade} onChange={(event) =>{
        setStudent({...student, grade: event.target.value})
      }} /><TextField id="outlined-basic" label="Section" variant="outlined" value={student.section} onChange={(event) =>{
        setStudent({...student, section: event.target.value})
      }} />
      <Button variant="contained" color="primary" onClick={createStudent}  >
        Create 
      </Button>
    </form>
    </>
  );
}

之前我在 Chrome 控制台中收到以下错误:

但我修复了它(或者我是这么想的),按照this article 中的建议添加了这个Chrome extension。这可能是我的属性没有显示的原因吗?

【问题讨论】:

    标签: javascript node.js reactjs mongodb express


    【解决方案1】:

    你需要安装cors

    npm install cors

    比在你的路由器上应用它

    import express from "express";
    import cors from "cors"; //Import Cors
    import { getStudents, createStudent} from "../controllers/student.js"
    import student from '../models/student.js';
    const app = express(); //Change it from express.Router() to express()
    
    app.use(cors()); //applied cors here
    app.get("/", getStudents); //res = response req=request
    app.post("/", createStudent); 
    export default app;
    

    【讨论】:

      【解决方案2】:

      如果您计划将来在生产中使用该项目,请不要使用cors。这是一个重大的安全风险。相反,请使用 Create React App 中内置的代理功能(假设您正在使用它)。

      https://create-react-app.dev/docs/proxying-api-requests-in-development

      当然,如果您只是将此项目用作沙盒或反复试验,那也没关系。请记住不要在生产环境中执行此操作。

      【讨论】:

        猜你喜欢
        • 2016-09-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-26
        • 1970-01-01
        • 2019-12-01
        • 1970-01-01
        相关资源
        最近更新 更多