Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/420.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 服务器上未显示对象属性_Javascript_Node.js_Reactjs_Mongodb_Express - Fatal编程技术网

Javascript 服务器上未显示对象属性

Javascript 服务器上未显示对象属性,javascript,node.js,reactjs,mongodb,express,Javascript,Node.js,Reactjs,Mongodb,Express,我跟随MERN堆栈,因为我想看看所有的片段是如何编织在一起的,以便更好地理解它。我的问题是,当我去加载在客户端输入的服务器对象属性(studentName和regNo)时,除了那些具有默认值的属性外,它们不会出现。当我转到http://localhost:5000/students/我看到了以下几点: 在服务器端,我有以下内容: /server/models/student.js包含 import mongoose from 'mongoose'; const studentSchema=

我跟随MERN堆栈,因为我想看看所有的片段是如何编织在一起的,以便更好地理解它。我的问题是,当我去加载在客户端输入的服务器对象属性(
studentName
regNo
)时,除了那些具有默认值的属性外,它们不会出现。当我转到
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;

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;
/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 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;

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>
    </>
  );
}
import React,{useState}来自“React”;
从'@material ui/core/styles'导入{makeStyles};
从“@material ui/core/TextField”导入TextField;
从“@material ui/core/Button”导入按钮;
从“axios”导入axios;
const useStyles=makeStyles((主题)=>({
根目录:{
'& > *': {
边距:主题。间距(1),
宽度:'25ch',
},
},
}));
导出默认函数Create(){
const classes=useStyles();
常量[学生,设置学生]=使用状态({
区域编号:0,
学生姓名:“”,
等级:'',
节:“”
});//React hook。更新前端文本字段中的数据
const createStudent=()=>{
axios.post(“http://localhost:5000/students“,学生)
} 
返回(
创造学生
{
setStudent({…student,regNo:event.target.value})
}}  />
{
setStudent({…student,studentName:event.target.value})
}} />{
setStudent({…学生,年级:event.target.value})
}} />{
setStudent({…student,节:event.target.value})
}} />
创造
);
}
早些时候,我在Chrome控制台中遇到以下错误:

但是我修正了它(或者我是这么想的),按照中的建议添加了这个。这就是我的属性没有显示的原因吗?

您需要安装cors

npm是否安装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;

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

当然,如果您只是将此项目用作沙箱或试错,那么这并不重要。记住不要在生产中这样做