我正在处理我的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
我的contactUs.js文件
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.controller.js文件
import Contact from '../models/contactUs.model'
import _ from 'lodash'
import errorHandler from '../helpers/dbErrorHandler'
const create = (req, res, next) => {
const contact = new Contact(req.body)
contact.save((err, result) => {
if (err) {
return res.status(400).json({
error: errorHandler.getErrorMessage(err)
})
}
res.status(200).json({
message: "You Complained Successfully!"
})
})
}
export default create
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)
期待:)
答案 0 :(得分:0)
您没有提供任何错误消息,但我认为问题出在您的clickSubmit方法中,在contactUs对象中,您将字段“名称”设置了两次,而不是fname和lname。