服务器和前端之间的通信问题

发布于 2025-01-11 06:30:51 字数 10805 浏览 0 评论 0原文

orderjs(前端)中的两个函数只是将数据插入到数据库中,但之后,它给了我 400 个资源,页面刚刚重新加载,网络上的所有消息都被自己删除,所以 loadUser 函数不会不起作用,路线改变也不起作用 这里的问题是服务器显示他发送了包含该对象的对象,但客户端没有收到任何内容 它收到 400 res 状态,但页面重新加载速度非常快

App.js

import React, {Component} from 'react';
import {BrowserRouter as Router,
        Routes,
        Route
      } from 'react-router-dom';
import './App.css';
import Navbar from './components/Navbar/Navbar';
import Home from './components/Home/Home';
import Footer from './components/Footer/Footer';
import Order from './components/Order/Order';

import NoPage from './components/nopage/noPage';
import Collab from './components/collaboration/collaboration';
import Art from './components/art/art';

import OrderCompleted from './components/OrderCompleted/OrderCompleted';



const initialState= {
   
    user: {
      id: '',
      firstname: '',
      lastname: '',
      email:'',
      mobilenumber:'',
      adress:'',
      city: '',
      size:'',
      quantity: '',
      joined:''
    }


  }






class App extends Component {
 constructor(){
  super();
  this.state= initialState;
}
   

    loadUser = (data) => {
  this.setState( {user:
      {       id: data.id,
      firstname: data.firstname,
      lastname:data.lastname ,
      email:data.email,
      mobilenumber:data.mobilenumber,
      adress:data.adress,
      city: data.city,
      size:data.size,
      quantity: data.quantity,
      joined:data.joined
        }})
}


render() {
    return (
     <>
  <Router>
      <Routes>
        <Route path="/" element={<Navbar /> }>
        <Route index element={<Home />} />
        <Route path="order"> 
          <Route index element={<Order  loadUser={this.loadUser}/>} />
          <Route path="orderCompleted" element={<OrderCompleted />} />
        </Route>
      
          <Route path="collab" element={<Collab />} />
          <Route path="art" element={<Art />} />
         
          <Route path="*" element={<NoPage />} />
         </Route>
      </Routes>
    </Router>
<Footer/>
</>
    );
  }
 

} 

export default App;

Order.js (前端)

import React from 'react';
import MERCH from './MERCH.jpg';
import {Row, Col, Button, Form} from 'react-bootstrap';
import 'bootstrap/dist/css/bootstrap.min.css';
import './Order.css';
import { useState } from 'react';
import { useNavigate} from "react-router";

function Order(props) {
   const navigate = useNavigate();


  const [firstName, setFirstName] = useState('');
  const [lastName, setLastName] = useState('');
  const [email, setEmail] = useState('');
  const [mobileNumber, setMobileNumber] = useState('');
  const [adress, setAddress] = useState('');
  const [city, setCity] = useState('');
  const [size, setSize] = useState('');
  const [quantity, setQuantity] = useState('1');






 const onOrderSubmitCOD = () =>  {
  fetch('http://localhost:3000/orderCOD', {
      method: 'post',
      mode: 'cors',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify({
        firstname: firstName,
        lastname:lastName,
        email: email,
        mobilenumber: mobileNumber,
        adress: adress,
        city: city,
        size:size,
        quantity: quantity

      })
    })
      .then(response => response.json())
      .then(user => {
        console.log(user)
        if (user.id) {
         
          props.loadUser(user);
          
          navigate('/order/orderCompleted'); 
        }
      })
      .catch(err => console.log(err));
  }

 const onOrderSubmitCP = () => {
  fetch('http://localhost:3000/orderCP', {
      method: 'post',
      mode: 'cors',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify({
        firstname: firstName,
        lastname:lastName,
        email: email,
        mobilenumber: mobileNumber,
        adress: adress,
        city: city,
        size:size,
        quantity: quantity

      })
    })
      .then(response => response.json())

      .then(usercp => {
        
        if (usercp.id) {
         
          props.loadUser(usercp);
          console.log(usercp)
          navigate('/order/orderCompleted');
          
        }
      })
      .catch(err => console.log(err));
  }



    return(
    <div style={{ width: '50%' }} className="center bg-black  b   br3 pa3 ma4  bw2 shadow-1">
    <Form className="font " style={{ width: '90%'  }}>
      <Row>
        <Col>
          <Form.Control 
          placeholder="First name"
          value={firstName}
          onChange={event => setFirstName(event.target.value)} />
        </Col>
        <Col>
          <Form.Control
           placeholder="Last name"
           value={lastName}
           onChange={event => setLastName(event.target.value)} />
        </Col>
      </Row>
      <Row className="mb-3 mt2">
        <Form.Group as={Col} controlId="formGridEmail">
          <Form.Label>Email</Form.Label>
          <Form.Control type="email" 
          placeholder="Enter email"
          value={email}
          onChange={event => setEmail(event.target.value)} />
        </Form.Group>

        <Form.Group as={Col} controlId="formGridPassword">
          <Form.Label>Mobile number</Form.Label>
          <Form.Control type="number" 
          placeholder="Mobile"
          value={mobileNumber}
          onChange={event => setMobileNumber(event.target.value)} />
        </Form.Group>
      </Row>

      <Form.Group className="mb-3" controlId="formGridAddress1">
        <Form.Label>Address</Form.Label>
        <Form.Control 
        placeholder="Adress" 
        value={adress}
        onChange={event => setAddress(event.target.value)}/>
      </Form.Group>

    

      <Row className="mb-3">
        <Form.Group as={Col} controlId="formGridCity">
          <Form.Label>City</Form.Label>
          <Form.Control
          value={city}
          onChange={event => setCity(event.target.value)}  />
        </Form.Group>

        

        <Form.Group as={Col} controlId="formGridZip">
          <Form.Label>Size</Form.Label>
          <Form.Select 
          value={size}
          onChange={event => setSize(event.target.value)}>
            <option>Choose...</option>
            <option>S</option>
            <option>M</option>
            <option>L</option>
            <option>XL</option>
            
          </Form.Select>
        </Form.Group>
        <Form.Group as={Col} controlId="formGridZip">
          <Form.Label>Quantity</Form.Label>
          <Form.Select 
          
          value={quantity}
          onChange={event => setQuantity(event.target.value)}>
            <option>1</option>
            <option>2</option>
            <option>3</option>
            <option>4</option>
            <option>5</option>
            <option>6</option>
            <option>7</option>
            <option>8</option>
            <option>9</option>
            <option>10</option>
            
          </Form.Select>
        </Form.Group>
      </Row>
    

    
      <div  className=" gap-2 mt4 b">
     <Button onClick={onOrderSubmitCOD} className="b" variant="outline-light"  type="Submit" >
        ORDER (COD)
      </Button>
      
      </div>
      <div  className=" gap-2 mt4 b">
      <Button onClick={onOrderSubmitCP} className="b" variant="outline-light"  type="Submit">
            ORDER (CP)
      </Button>
     </div>
</Form>


</div>

)
}
export default Order;

server.js (后端)

const express = require('express');

const cors = require('cors');

const knex = require('knex');

const order=require('./controllers/order');







const db = knex({
 
  client: 'pg',
  connection: {
    host : '127.0.0.1',
    user : 'postgres',
    password : 'test',
    database : 'dosei'
  }
});





const app = express();
app.use(express.json());
app.use(cors());

app.get('/',(req,res)=>{
    res.send('its working')
})

app.post('/orderCOD',(req, res)=>order.handleOrderCOD(req, res, db))

app.post('/orderCP',(req, res)=>order.handleOrderCP(req, res, db))



app.get('/collab' , (req, res)=>{
  res.send('its working collab')
} )

app.get('/art', (req, res)=>{
  res.send('its working art')
})




app.listen(3000, ()=> {
  console.log('app is running on port 3000');
})

order.js (后端)

 const handleOrderCOD = (req,res, db) => {
const {firstname, lastname, email, mobilenumber, adress, city, size, quantity} = req.body;
if(!firstname || !lastname || !email || !mobilenumber || !adress || !city || !size || !quantity)
    {return  res.status(400).json('no data to load')};
db.insert({
        
        firstname: firstname,
        lastname:lastname,
        email:email,
        mobilenumber:mobilenumber,
        adress:adress,
        city:city,
        size:size,
        quantity:quantity,
        joined: new Date()

       
    
    })

.into('orders')
.returning('*')
 .catch(err=>res.status(400).json('unable to order1'))
    .then(user =>{
        if(user){
              res.json(user[0]) 
        } else{
            res.status(400).json('unable to order1')
        }
          
    })
    .catch(err=>res.status(400).json('unable to order2'))
}

 const handleOrderCP = (req,res, db) => {
const {firstname, lastname, email, mobilenumber, adress, city, size, quantity} = req.body;
if(!firstname || !lastname || !email || !mobilenumber || !adress || !city || !size || !quantity)
    {return  res.status(400).json('no data to load')};

db.insert({
        
        firstname: firstname,
        lastname:lastname,
        email:email,
        mobilenumber:mobilenumber,
        adress:adress,
        city:city,
        size:size,
        quantity:quantity,
        joined: new Date()

       
    
    })

.into('orderscp')
.returning('*')

    .then(usercp =>{
        if(usercp){

              res.json(usercp[0])
             

        } else{
            res.status(400).json('unable to order1')
        }

    })
    .catch(err=>res.status(400).json('unable to order2'))
}



    



    

module.exports={
    handleOrderCOD,
    handleOrderCP
}

The two functions in orderjs (frontend) work just with inserting the data to the database but after that, it gives me 400 res, and the page just reloaded itself and all the messages on the network just got deleted by itself so the loadUser funct don't work and the route change don't work also
the problem here is that the server shows that he sent the object that contain the object but the client don't receive anything
it receives a 400 res status but the page get reload itself so fast

App.js

import React, {Component} from 'react';
import {BrowserRouter as Router,
        Routes,
        Route
      } from 'react-router-dom';
import './App.css';
import Navbar from './components/Navbar/Navbar';
import Home from './components/Home/Home';
import Footer from './components/Footer/Footer';
import Order from './components/Order/Order';

import NoPage from './components/nopage/noPage';
import Collab from './components/collaboration/collaboration';
import Art from './components/art/art';

import OrderCompleted from './components/OrderCompleted/OrderCompleted';



const initialState= {
   
    user: {
      id: '',
      firstname: '',
      lastname: '',
      email:'',
      mobilenumber:'',
      adress:'',
      city: '',
      size:'',
      quantity: '',
      joined:''
    }


  }






class App extends Component {
 constructor(){
  super();
  this.state= initialState;
}
   

    loadUser = (data) => {
  this.setState( {user:
      {       id: data.id,
      firstname: data.firstname,
      lastname:data.lastname ,
      email:data.email,
      mobilenumber:data.mobilenumber,
      adress:data.adress,
      city: data.city,
      size:data.size,
      quantity: data.quantity,
      joined:data.joined
        }})
}


render() {
    return (
     <>
  <Router>
      <Routes>
        <Route path="/" element={<Navbar /> }>
        <Route index element={<Home />} />
        <Route path="order"> 
          <Route index element={<Order  loadUser={this.loadUser}/>} />
          <Route path="orderCompleted" element={<OrderCompleted />} />
        </Route>
      
          <Route path="collab" element={<Collab />} />
          <Route path="art" element={<Art />} />
         
          <Route path="*" element={<NoPage />} />
         </Route>
      </Routes>
    </Router>
<Footer/>
</>
    );
  }
 

} 

export default App;

Order.js (frontend)

import React from 'react';
import MERCH from './MERCH.jpg';
import {Row, Col, Button, Form} from 'react-bootstrap';
import 'bootstrap/dist/css/bootstrap.min.css';
import './Order.css';
import { useState } from 'react';
import { useNavigate} from "react-router";

function Order(props) {
   const navigate = useNavigate();


  const [firstName, setFirstName] = useState('');
  const [lastName, setLastName] = useState('');
  const [email, setEmail] = useState('');
  const [mobileNumber, setMobileNumber] = useState('');
  const [adress, setAddress] = useState('');
  const [city, setCity] = useState('');
  const [size, setSize] = useState('');
  const [quantity, setQuantity] = useState('1');






 const onOrderSubmitCOD = () =>  {
  fetch('http://localhost:3000/orderCOD', {
      method: 'post',
      mode: 'cors',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify({
        firstname: firstName,
        lastname:lastName,
        email: email,
        mobilenumber: mobileNumber,
        adress: adress,
        city: city,
        size:size,
        quantity: quantity

      })
    })
      .then(response => response.json())
      .then(user => {
        console.log(user)
        if (user.id) {
         
          props.loadUser(user);
          
          navigate('/order/orderCompleted'); 
        }
      })
      .catch(err => console.log(err));
  }

 const onOrderSubmitCP = () => {
  fetch('http://localhost:3000/orderCP', {
      method: 'post',
      mode: 'cors',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify({
        firstname: firstName,
        lastname:lastName,
        email: email,
        mobilenumber: mobileNumber,
        adress: adress,
        city: city,
        size:size,
        quantity: quantity

      })
    })
      .then(response => response.json())

      .then(usercp => {
        
        if (usercp.id) {
         
          props.loadUser(usercp);
          console.log(usercp)
          navigate('/order/orderCompleted');
          
        }
      })
      .catch(err => console.log(err));
  }



    return(
    <div style={{ width: '50%' }} className="center bg-black  b   br3 pa3 ma4  bw2 shadow-1">
    <Form className="font " style={{ width: '90%'  }}>
      <Row>
        <Col>
          <Form.Control 
          placeholder="First name"
          value={firstName}
          onChange={event => setFirstName(event.target.value)} />
        </Col>
        <Col>
          <Form.Control
           placeholder="Last name"
           value={lastName}
           onChange={event => setLastName(event.target.value)} />
        </Col>
      </Row>
      <Row className="mb-3 mt2">
        <Form.Group as={Col} controlId="formGridEmail">
          <Form.Label>Email</Form.Label>
          <Form.Control type="email" 
          placeholder="Enter email"
          value={email}
          onChange={event => setEmail(event.target.value)} />
        </Form.Group>

        <Form.Group as={Col} controlId="formGridPassword">
          <Form.Label>Mobile number</Form.Label>
          <Form.Control type="number" 
          placeholder="Mobile"
          value={mobileNumber}
          onChange={event => setMobileNumber(event.target.value)} />
        </Form.Group>
      </Row>

      <Form.Group className="mb-3" controlId="formGridAddress1">
        <Form.Label>Address</Form.Label>
        <Form.Control 
        placeholder="Adress" 
        value={adress}
        onChange={event => setAddress(event.target.value)}/>
      </Form.Group>

    

      <Row className="mb-3">
        <Form.Group as={Col} controlId="formGridCity">
          <Form.Label>City</Form.Label>
          <Form.Control
          value={city}
          onChange={event => setCity(event.target.value)}  />
        </Form.Group>

        

        <Form.Group as={Col} controlId="formGridZip">
          <Form.Label>Size</Form.Label>
          <Form.Select 
          value={size}
          onChange={event => setSize(event.target.value)}>
            <option>Choose...</option>
            <option>S</option>
            <option>M</option>
            <option>L</option>
            <option>XL</option>
            
          </Form.Select>
        </Form.Group>
        <Form.Group as={Col} controlId="formGridZip">
          <Form.Label>Quantity</Form.Label>
          <Form.Select 
          
          value={quantity}
          onChange={event => setQuantity(event.target.value)}>
            <option>1</option>
            <option>2</option>
            <option>3</option>
            <option>4</option>
            <option>5</option>
            <option>6</option>
            <option>7</option>
            <option>8</option>
            <option>9</option>
            <option>10</option>
            
          </Form.Select>
        </Form.Group>
      </Row>
    

    
      <div  className=" gap-2 mt4 b">
     <Button onClick={onOrderSubmitCOD} className="b" variant="outline-light"  type="Submit" >
        ORDER (COD)
      </Button>
      
      </div>
      <div  className=" gap-2 mt4 b">
      <Button onClick={onOrderSubmitCP} className="b" variant="outline-light"  type="Submit">
            ORDER (CP)
      </Button>
     </div>
</Form>


</div>

)
}
export default Order;

server.js (backend)

const express = require('express');

const cors = require('cors');

const knex = require('knex');

const order=require('./controllers/order');







const db = knex({
 
  client: 'pg',
  connection: {
    host : '127.0.0.1',
    user : 'postgres',
    password : 'test',
    database : 'dosei'
  }
});





const app = express();
app.use(express.json());
app.use(cors());

app.get('/',(req,res)=>{
    res.send('its working')
})

app.post('/orderCOD',(req, res)=>order.handleOrderCOD(req, res, db))

app.post('/orderCP',(req, res)=>order.handleOrderCP(req, res, db))



app.get('/collab' , (req, res)=>{
  res.send('its working collab')
} )

app.get('/art', (req, res)=>{
  res.send('its working art')
})




app.listen(3000, ()=> {
  console.log('app is running on port 3000');
})

order.js (backend)

 const handleOrderCOD = (req,res, db) => {
const {firstname, lastname, email, mobilenumber, adress, city, size, quantity} = req.body;
if(!firstname || !lastname || !email || !mobilenumber || !adress || !city || !size || !quantity)
    {return  res.status(400).json('no data to load')};
db.insert({
        
        firstname: firstname,
        lastname:lastname,
        email:email,
        mobilenumber:mobilenumber,
        adress:adress,
        city:city,
        size:size,
        quantity:quantity,
        joined: new Date()

       
    
    })

.into('orders')
.returning('*')
 .catch(err=>res.status(400).json('unable to order1'))
    .then(user =>{
        if(user){
              res.json(user[0]) 
        } else{
            res.status(400).json('unable to order1')
        }
          
    })
    .catch(err=>res.status(400).json('unable to order2'))
}

 const handleOrderCP = (req,res, db) => {
const {firstname, lastname, email, mobilenumber, adress, city, size, quantity} = req.body;
if(!firstname || !lastname || !email || !mobilenumber || !adress || !city || !size || !quantity)
    {return  res.status(400).json('no data to load')};

db.insert({
        
        firstname: firstname,
        lastname:lastname,
        email:email,
        mobilenumber:mobilenumber,
        adress:adress,
        city:city,
        size:size,
        quantity:quantity,
        joined: new Date()

       
    
    })

.into('orderscp')
.returning('*')

    .then(usercp =>{
        if(usercp){

              res.json(usercp[0])
             

        } else{
            res.status(400).json('unable to order1')
        }

    })
    .catch(err=>res.status(400).json('unable to order2'))
}



    



    

module.exports={
    handleOrderCOD,
    handleOrderCP
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文