Node.js 如果出现400错误,如何解决API问题?

Node.js 如果出现400错误,如何解决API问题?,node.js,reactjs,Node.js,Reactjs,我正在做我的react项目,并试图添加一个页面。所有型号、控制器和路线均已设置。但是表单的数据(来自我新添加的页面)并没有将数据发布到mongodb集合中。我还创建了API。。但数据并未公布 我认为创建的API存在问题,它给出了400错误。。请看一下我的代码,我不明白背后的真正原因。这是密码 这是我的api-contactUs.js文件 const create = (contactUs) => { return fetch('/api/contactUs', {

我正在做我的react项目,并试图添加一个页面。所有型号、控制器和路线均已设置。但是表单的数据(来自我新添加的页面)并没有将数据发布到mongodb集合中。我还创建了API。。但数据并未公布

我认为创建的API存在问题,它给出了400错误。。请看一下我的代码,我不明白背后的真正原因。这是密码

这是我的api-contactUs.js文件

const create = (contactUs) => {
    return fetch('/api/contactUs', {
        method: 'POST',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(contactUs)
      })
      .then((response) => {
        return response.json()
      }).catch((err) => console.log(err))
  }
export default create
import React from 'react';
import PropTypes from 'prop-types'
import {withStyles} from 'material-ui/styles'
import Card, {CardActions, CardContent} from 'material-ui/Card'
import Icon from 'material-ui/Icon'
import Button from 'material-ui/Button'
import TextField from 'material-ui/TextField'
import Typography from 'material-ui/Typography'
import create from './api-contactUs.js'
import { Grid } from 'material-ui';
import Dialog, {DialogActions, DialogContent, DialogContentText, DialogTitle} from 'material-ui/Dialog'


const styles = theme => ({
contactWrapper :{
    backgroundImage: `url(${require('../assets/images/contactmain.svg')})`,
    backgroundSize: 'cover',
    backgroundPosition: '50%',  
    height: '115vh',
    backgroundRepeat: 'no-repeat' 

 },
 mycontainer:{
    display: 'flex',
    flexDirection: 'row',
    flexWrap: 'wrap',
    width: '100%',
    justifyContent: 'center',
    alignItems: 'center',
    fontFamily: 'Helvetica,sans-serif'
 },
 contactHeader:{
    padding: '20px 15px',
    textAlign: 'left',
 },
 logo:{
    width: '150px',
    height: '100%'
 },
 contactDes:{
     padding: '0 15px',
     margin: '80px 0 100px',
     flexDirection: 'column',
     display: 'flex',
     alignItems: 'center',
     '& h1': {
         fontSize: '40px',
         lineHeight: '50px',
         margin: '0 0 30px',
         fontFamily: 'Canela Deck Bold !important',
         color: '#21d192',
         fontWeight: '600',
         '& span':{
             color: '#fff',
             display: 'block'   
         }
     },
     '& p':{
        color: '#fff',
        fontSize: '14px',
        letterSpacing: '.8px',
        lineHeight: '21px',
        margin: '0 0 30px',
        display: 'block',
        fontFamily: 'inherit',

     },
     '& ul':{
         color: '#fff',
         fontSize: '14px',
         letterSpacing: '.8px',
         lineHeight: '22px',
         paddingLeft: '15px',
         margin: '0',
         fontFamily: 'inherit',
        '& li':{
            marginBottom: '10px'
        }
     }
 },
 contactForm: {
    flexDirection: 'column',
    display: 'flex',
    alignItems: 'center'
 },
 card:{
    minWidth: '520px',
    maxWidth: '520px',

 },
 error: {
    verticalAlign: 'middle'
  },
 textField:{
    width: 454,
 },
 typography:{
     margin: '30px 0 20px',
     textAlign: 'center !important',
     fontSize: '17px',
     lineHeight: '24px',
     fontWeight: '500',
     color: 'rgb(34, 34, 34)',
     fontFamily: 'inherit',
     color: '#222',
     fontStyle: 'oblique'
 },
 submit:{
    margin: 'auto',
    marginBottom: theme.spacing.unit * 4
 }

})

class ContactUs extends React.Component {
    state = {
        fname: '',
        lname: '',
        email: '',
        phone_no: '',
        description: '',
        open: false,
        error: ''
    }
    handleChange = name => event => {
        this.setState({[name]: event.target.value})
      }

    clickSubmit = () => {
        const contactUs = {
          name: this.state.fname || undefined,
          name: this.state.lname || undefined,
          email: this.state.email || undefined,
          phone_no: this.state.phone_no || undefined,
          description: this.state.description || undefined,
        }
        create(contactUs).then((data) => {
          if (data.error) {
            this.setState({error: data.error})
          } else {
            this.setState({error: '', open: true})
          }
        })
    }
    render(){
        const {classes} = this.props;
        return(
            <div className={classes.contactWrapper}>
                <Grid >
                    <Grid container item xs={12} className={classes.contactHeader}><a href="/"><img className={classes.logo} src={require('../assets/images/Main_logo.svg')}/></a></Grid>
                    <Grid item md={12} className={classes.mycontainer}>
                        <Grid item md={6} sm={12} className={classes.contactDes}>
                            <div style={{minWidth: '520px', maxWidth: '520px'}}>
                                <h1> Get the Local Services
                                    <span>you need!</span>
                                </h1>
                                <p>Professional Services is the top local services providing app, helping you to provide services faster and more efficiently. Our services providing, Professional Services Platform, can help you:</p>
                                <ul>
                                    <li>Find the best talent with the support of a dedicated account manager.</li>
                                    <li>Find the best talent with the support of a dedicated.</li>
                                    <li>Find the best talent with the support.</li>

                                </ul>

                            </div>

                        </Grid>
                        <Grid item md={6} sm={12} className={classes.contactForm}>
                            <Card className={classes.card}>
                                <CardContent style={{width: '470px'}}>
                                    <Typography className={classes.typography}>For any complaint or query, fill this out and we’ll contact you, as soon as possible.</Typography>
                                    <TextField id="fname" name="fname" label="First Name" value={this.state.fname} onChange={this.handleChange('fname')} className={classes.textField}  margin="normal"/><br/>
                                    <TextField id="lname" name="lname" label="Last Name" value={this.state.lname} onChange={this.handleChange('lname')} className={classes.textField}  margin="normal"/><br/>
                                    <TextField id="email" name="email" type="email" label="Business Email" value={this.state.email} onChange={this.handleChange('email')} className={classes.textField} margin="normal"/><br/>
                                    <TextField id="phone_no" name="phone_no" label="Phone Number" value={this.state.phone_no} onChange={this.handleChange('phone_no')} className={classes.textField}  margin="normal"/><br/>
                                    <TextField
                                        id="multiline-flexible"
                                        label="Post your request"
                                        multiline
                                        row="2"
                                        value={this.state.description}
                                        onChange={this.handleChange('description')}
                                        className={classes.textField}
                                        margin="normal"
                                    /><br/>
                                    {
                                        this.state.error && (<Typography component="p" color="error">
                                        <Icon color="error" className={classes.error}>error</Icon>
                                        {this.state.error}</Typography>)
                                    }

                                    <br /><br />

                                </CardContent>
                                <CardActions>
                                 <Button color="secondary" variant="raised" onClick={this.clickSubmit} className={classes.submit}>Submit</Button>
                                <br />
                                </CardActions>

                            </Card>
                            <Dialog open={this.state.open} disableBackdropClick={true}>
                                <DialogTitle>Request</DialogTitle>
                                <DialogContent>
                                <DialogContentText>
                                   Your Request is registerd!
                                </DialogContentText>
                                </DialogContent>
                                {/* <DialogActions>
                                <Link to="/signin">
                                    <Button color="primary" autoFocus="autoFocus" variant="raised">
                                    Sign In
                                    </Button>
                                </Link>
                                </DialogActions> */}
                            </Dialog>

                        </Grid>
                    </Grid>
                </Grid>

            </div>
        );
    }
}
ContactUs.propTypes = {
    classes: PropTypes.object.isRequired
  }

export default withStyles(styles)(ContactUs);
我的contactUs.js文件

const create = (contactUs) => {
    return fetch('/api/contactUs', {
        method: 'POST',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(contactUs)
      })
      .then((response) => {
        return response.json()
      }).catch((err) => console.log(err))
  }
export default create
import React from 'react';
import PropTypes from 'prop-types'
import {withStyles} from 'material-ui/styles'
import Card, {CardActions, CardContent} from 'material-ui/Card'
import Icon from 'material-ui/Icon'
import Button from 'material-ui/Button'
import TextField from 'material-ui/TextField'
import Typography from 'material-ui/Typography'
import create from './api-contactUs.js'
import { Grid } from 'material-ui';
import Dialog, {DialogActions, DialogContent, DialogContentText, DialogTitle} from 'material-ui/Dialog'


const styles = theme => ({
contactWrapper :{
    backgroundImage: `url(${require('../assets/images/contactmain.svg')})`,
    backgroundSize: 'cover',
    backgroundPosition: '50%',  
    height: '115vh',
    backgroundRepeat: 'no-repeat' 

 },
 mycontainer:{
    display: 'flex',
    flexDirection: 'row',
    flexWrap: 'wrap',
    width: '100%',
    justifyContent: 'center',
    alignItems: 'center',
    fontFamily: 'Helvetica,sans-serif'
 },
 contactHeader:{
    padding: '20px 15px',
    textAlign: 'left',
 },
 logo:{
    width: '150px',
    height: '100%'
 },
 contactDes:{
     padding: '0 15px',
     margin: '80px 0 100px',
     flexDirection: 'column',
     display: 'flex',
     alignItems: 'center',
     '& h1': {
         fontSize: '40px',
         lineHeight: '50px',
         margin: '0 0 30px',
         fontFamily: 'Canela Deck Bold !important',
         color: '#21d192',
         fontWeight: '600',
         '& span':{
             color: '#fff',
             display: 'block'   
         }
     },
     '& p':{
        color: '#fff',
        fontSize: '14px',
        letterSpacing: '.8px',
        lineHeight: '21px',
        margin: '0 0 30px',
        display: 'block',
        fontFamily: 'inherit',

     },
     '& ul':{
         color: '#fff',
         fontSize: '14px',
         letterSpacing: '.8px',
         lineHeight: '22px',
         paddingLeft: '15px',
         margin: '0',
         fontFamily: 'inherit',
        '& li':{
            marginBottom: '10px'
        }
     }
 },
 contactForm: {
    flexDirection: 'column',
    display: 'flex',
    alignItems: 'center'
 },
 card:{
    minWidth: '520px',
    maxWidth: '520px',

 },
 error: {
    verticalAlign: 'middle'
  },
 textField:{
    width: 454,
 },
 typography:{
     margin: '30px 0 20px',
     textAlign: 'center !important',
     fontSize: '17px',
     lineHeight: '24px',
     fontWeight: '500',
     color: 'rgb(34, 34, 34)',
     fontFamily: 'inherit',
     color: '#222',
     fontStyle: 'oblique'
 },
 submit:{
    margin: 'auto',
    marginBottom: theme.spacing.unit * 4
 }

})

class ContactUs extends React.Component {
    state = {
        fname: '',
        lname: '',
        email: '',
        phone_no: '',
        description: '',
        open: false,
        error: ''
    }
    handleChange = name => event => {
        this.setState({[name]: event.target.value})
      }

    clickSubmit = () => {
        const contactUs = {
          name: this.state.fname || undefined,
          name: this.state.lname || undefined,
          email: this.state.email || undefined,
          phone_no: this.state.phone_no || undefined,
          description: this.state.description || undefined,
        }
        create(contactUs).then((data) => {
          if (data.error) {
            this.setState({error: data.error})
          } else {
            this.setState({error: '', open: true})
          }
        })
    }
    render(){
        const {classes} = this.props;
        return(
            <div className={classes.contactWrapper}>
                <Grid >
                    <Grid container item xs={12} className={classes.contactHeader}><a href="/"><img className={classes.logo} src={require('../assets/images/Main_logo.svg')}/></a></Grid>
                    <Grid item md={12} className={classes.mycontainer}>
                        <Grid item md={6} sm={12} className={classes.contactDes}>
                            <div style={{minWidth: '520px', maxWidth: '520px'}}>
                                <h1> Get the Local Services
                                    <span>you need!</span>
                                </h1>
                                <p>Professional Services is the top local services providing app, helping you to provide services faster and more efficiently. Our services providing, Professional Services Platform, can help you:</p>
                                <ul>
                                    <li>Find the best talent with the support of a dedicated account manager.</li>
                                    <li>Find the best talent with the support of a dedicated.</li>
                                    <li>Find the best talent with the support.</li>

                                </ul>

                            </div>

                        </Grid>
                        <Grid item md={6} sm={12} className={classes.contactForm}>
                            <Card className={classes.card}>
                                <CardContent style={{width: '470px'}}>
                                    <Typography className={classes.typography}>For any complaint or query, fill this out and we’ll contact you, as soon as possible.</Typography>
                                    <TextField id="fname" name="fname" label="First Name" value={this.state.fname} onChange={this.handleChange('fname')} className={classes.textField}  margin="normal"/><br/>
                                    <TextField id="lname" name="lname" label="Last Name" value={this.state.lname} onChange={this.handleChange('lname')} className={classes.textField}  margin="normal"/><br/>
                                    <TextField id="email" name="email" type="email" label="Business Email" value={this.state.email} onChange={this.handleChange('email')} className={classes.textField} margin="normal"/><br/>
                                    <TextField id="phone_no" name="phone_no" label="Phone Number" value={this.state.phone_no} onChange={this.handleChange('phone_no')} className={classes.textField}  margin="normal"/><br/>
                                    <TextField
                                        id="multiline-flexible"
                                        label="Post your request"
                                        multiline
                                        row="2"
                                        value={this.state.description}
                                        onChange={this.handleChange('description')}
                                        className={classes.textField}
                                        margin="normal"
                                    /><br/>
                                    {
                                        this.state.error && (<Typography component="p" color="error">
                                        <Icon color="error" className={classes.error}>error</Icon>
                                        {this.state.error}</Typography>)
                                    }

                                    <br /><br />

                                </CardContent>
                                <CardActions>
                                 <Button color="secondary" variant="raised" onClick={this.clickSubmit} className={classes.submit}>Submit</Button>
                                <br />
                                </CardActions>

                            </Card>
                            <Dialog open={this.state.open} disableBackdropClick={true}>
                                <DialogTitle>Request</DialogTitle>
                                <DialogContent>
                                <DialogContentText>
                                   Your Request is registerd!
                                </DialogContentText>
                                </DialogContent>
                                {/* <DialogActions>
                                <Link to="/signin">
                                    <Button color="primary" autoFocus="autoFocus" variant="raised">
                                    Sign In
                                    </Button>
                                </Link>
                                </DialogActions> */}
                            </Dialog>

                        </Grid>
                    </Grid>
                </Grid>

            </div>
        );
    }
}
ContactUs.propTypes = {
    classes: PropTypes.object.isRequired
  }

export default withStyles(styles)(ContactUs);
contactUs.routes.js文件

import express from 'express'
import contactUsCtrl from '../controllers/contactUs.controller'

const router = express.Router()

router.route('/api/contactUs/')

  .post(contactUsCtrl)


export default router
contactUs.model.js文件

import mongoose from 'mongoose'
import crypto from 'crypto'
const ContactSchema = new mongoose.Schema({
  fname: {
    type: String,
    trim: true,
    required: 'First Name is required'
  },
  lname: {
    type: String,
    trim: true,
  },
  email: {
    type: String,
    trim: true,
    match: [/.+\@.+\..+/, 'Please fill a valid email address'],
    required: 'Email is required'
  },
  phone_no: {
    type: String,
    trim: true,
    required: 'Phone no is required'
  },
  description: {
    type: String,
    trim: true,
    required: 'Submit the reason'
  }
}
)


export default mongoose.model('Contact', ContactSchema)

展望未来:)

您没有提供任何错误消息,但我认为问题在于您的clickSubmit方法,在contactUs对象中,您设置了两次字段“name”,而不是fname和lname

那是一个复制粘贴错误。。我在模型文件中设置的模型错误消息现在已消失。。但是API仍然提供400状态。你能告诉我,实际上无法将值存储在DB中的错误是什么吗?试着记录你收到的错误消息,看看它说了什么。当我提交表单API fetch显示400状态时,我理解,我问的是错误消息。Mongoose可能必须向您提供一条错误消息,描述发生的问题