我尝试将数据从表单传输到服务器,并且在传输错误500(POST http://localhost:3000/api/message 500(内部服务器错误))时。我进入了网络/预览标签,然后看到“发生了什么事情错误,请重试”。我不知道发生了什么
主文件:
const express = require('express')
const config = require('config')
const mongoose = require('mongoose')
const app = express()
app.use(express.json({extended:true}))
app.use ('/api' , require('./Routes/Message'))
const Port = config.get('port') || 5000
async function start() {
try {
await mongoose.connect(config.get("MongoURI"), {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex:true
})
app.listen(Port, () => console.log("sus"))
} catch (e) {
console.log(e.message)
process.exit(1);
}
}
start()
Message.js:
const {Router} = require("express")
const router = Router()
const {check, validatorResult} = require("express-validator")
const User = require("../models/Message")
router.post('/message', [check("email", "Incorrect email").isEmail()], async (req, res) => {
try {
let errors = validatorResult(req)
if (!errors.isEmpty()) {
return res.status(400).json({
errors: errors.array,
message: "Incorrect data"
})
}
let {name,email, phone,message} = req.body
let user = new User({name,email, phone,message})
await user.save()
res.status(201).json({message: "Message sent"})
} catch (e) {
res.status(500).json({message: "Something went wrong, try again"})
}
})
module.exports= router
表格:
import React from "react";
import {useState} from 'react'
import "../../css/App.css";
import {useHTTP} from "../../store/api";
export const Form=()=>{
const {loading,request}=useHTTP()
const [form,setForm]=useState({name:"",email:"",phone:"",message:""})
const SendMessage=async ()=>{
try {
const data=await request("/api/message","POST",{...form})
console.log(data)
}
catch (e) {
}
}
const change=(e)=>
{
setForm({...form,[e.target.name]:e.target.value})
}
return (
<div className="MainFifth-write">
<h2>text</h2>
<form method="post">
<input placeholder="text" required onChange={change} name="name"/>
<input placeholder="text" onChange={change} name="phone" required />
<input placeholder="text" onChange={change} name="email" required />
<br />
<textarea placeholder="text" onChange={change} name="message" required />
<br />
<input className="agree" required type="checkbox" />
<label>text</label>
<br />
<button onClick={SendMessage} className="submit" type="submit" disabled={loading}>send</button>
</form>
</div>
)
}
带有useHTTP的文件:
const useHTTP=()=>{
const [loading,setLoading]=useState(false);
const [error,setError]=useState(null);
const request=useCallback( async(url, method='GET', body=null,headers={})=>{
setLoading(true)
try {
if(body) {
body=JSON.stringify(body)
headers['Content-Type']='application/json'
}
const response=await fetch(url,{method,body,headers})
const data=await response.json()
if(!response.ok){
throw new Error(data.message||"Что-то пошло не так")
}
setLoading(false)
return data
}
catch (e) {
setLoading(false)
setError(e.message)
throw e
}
},[])
return {loading,request,error}
}
全部。
答案 0 :(得分:0)
我只是拼写了validateResult错误。