axios React+节点网页-更新端点引发404错误

9fkzdhlc  于 2022-11-05  发布在  iOS
关注(0)|答案(1)|浏览(129)

我已经设置了一个网页,通过用户输入搜索一个数字,如果它在SQL Server数据库中可用,2个文本框将显示使用AXIOS GET端点的数据。然后,我试图获得这些数据行的ID,如果用户需要UPDATE它,然后通过AXIOS PUT终结点UPDATE它。问题是一旦用户单击UPDATE按钮,就会引发错误PUT http://localhost:5000/api/customerOrder/[object%20Object],[object%20Object] 404 (Not Found)
"这就是我所尝试的"

服务器终结点:

dboperations.js

var config = require('./dbconfig');
const sql = require('mssql');

async function getallcustomerOrders(){
    try{
        let pool = await sql.connect(config);
        let orders = await pool.request()
            .query("SELECT * FROM [100].[dbo].[OELINCMT_SQL] order by ID desc");
        return orders.recordsets;
    }
    catch (error){
        console.log(error);
    }
}

async function getcustomerOrders(orderNumber){
    try{
        let pool = await sql.connect(config);
        let orders = await pool.request()
            .input('input_parameter', sql.NChar, orderNumber)
            .query("SELECT ID,cmt FROM [100].[dbo].[OELINCMT_SQL] where LTRIM(ord_no) = LTRIM(@input_parameter)");
        return orders.recordsets;
    }
    catch (error){
        console.log(error);
    }
}

async function updateComments(ID){
    try {
        let pool = await sql.connect(config);
        let orders = await pool.request()
            .input('ID', sql.NChar, ID)
            .query(`SELECT ID,cmt FROM [100].[dbo].[OELINCMT_SQL] WHERE ID = @ID`);

        let order = orders.recordset.length ? orders.recordset[0] : null;
        if (order) {
            await pool.request()
                .input('cmt', req.body.cmt)
                .query(`UPDATE [100].[dbo].[OELINCMT_SQL] SET cmt = @cmt WHERE ID = @ID;`);

            order = { ...order, ...req.body };

            res.json(order);
        } else {
            res.status(404).json({
                message: 'Record not found'
            });
        }
    } catch (error) {
        res.status(500).json(error);
    }
}

module.exports = {
    getallcustomerOrders : getallcustomerOrders,
    getcustomerOrders : getcustomerOrders,
    updateComments : updateComments
}

api.js

var Db = require('./dboperations');
var dboperations = require('./dboperations');

var express = require('express');
var bodyParser = require('body-parser');
var cors = require('cors');
const { request, response } = require('express');
var app = express();
var router = express.Router();

app.use(bodyParser.urlencoded({ extended: true}));
app.use(bodyParser.json());
app.use(cors());
app.use('/api', router);

router.use((request,response,next)=> {
    console.log('middleware');
    next();
})

router.route('/customerOrder').get((request,response)=>{
    dboperations.getallcustomerOrders().then(result => {
        response.json(result[0]);
        console.log(result[0]);
    })
})

router.route('/customerOrder/:orderNumber').get((request,response)=>{
    dboperations.getcustomerOrders(request.params.orderNumber).then(result => {
        response.json(result[0]);
        console.log(result[0]);
    })
})

router.route('customerOrder/:ID').put((request,response)=>{
    dboperations.updateComments(request.params.ID).then(result => {
        response.json(result[0]);
        console.log(result[0]);
    })
})

var port = process.env.PORT || 5000;
app.listen(port);
console.log('Customer Order API is running at ' + port);

dboperations.getcustomerOrders().then(result => {
    console.log(result);
})

dboperations.getallcustomerOrders().then(result => {
    console.log(result);
})

dboperations.updateComments().then(result => {
    console.log(result);
})

委托单位:
EmailFaxDetails.js:这是用户输入编号的页面

import React, { useState,useEffect } from 'react'
import FetchOrderDetails from './FetchOrderDetails';
import axios from 'axios'
import '../App.css';

const EmailFaxDetails = () => {

    const [orderNumber, setOrderNumber] = useState('');
    const [id, setId] = useState([]);
    const [isShown, setIsShown] = useState(false);

    const url = `http://localhost:5000/api/customerOrder/${orderNumber}`
      useEffect(() => {
        axios.get(url)
        .then(response => {
          console.log(response.data)
          setId(response.data)
        })
        .catch((err) => console.log(err));
      }, [url]);

  const handleChange = event => {
    setOrderNumber(event.target.value);
    console.log(event.target.value);
  };

  const handleClick = event => {
    event.preventDefault();
    setIsShown(true);
    console.log(orderNumber);

  }

    return(
        <div>

            <br></br>
            <br></br>
            Order Number: <input placeholder="Order Number" type="text" id="message" name="message" onChange={handleChange} value={orderNumber} autoComplete="off" />
                {id.map((idnum) => (
                    <div key={idnum.ID}>
                      <br></br>
                      ID : {idnum.ID}
                    </div>
                ))}

            <button onClick={handleClick}>Search</button>
            {isShown && <FetchOrderDetails ord_no={orderNumber} ID={id}/>}
        </div>
    )
}

export default EmailFaxDetails;

FetchOrderDetails.js:在此页面中,如果SQL服务器中提供了该数字,则用户将获得输出,然后进行相应的更新。

import React, { useEffect, useState } from 'react'
import axios from 'axios'
import '../App.css';

const FetchOrderDetails = ({ord_no,ID}) => {
    const [data, setData] = useState([]);

    const url = `http://localhost:5000/api/customerOrder/${ord_no}`
      useEffect(() => {
        axios.get(url)
        .then(response => {
          console.log(response.data)
          setData(response.data)
        })
        .catch((err) => console.log(err));
      }, [url]);

    const url2 = `http://localhost:5000/api/customerOrder/${ID}`
    const onSubmit = () => {
        axios.put(url2)
        .then((response) => {
          if (response.status === 200) {
            alert("Comment successfully updated");
            ID.history.push(`/customerOrder/${ord_no}`);
          } else Promise.reject();
        })
        .catch((err) => alert("Something went wrong"));
      }

    if(data) {
        return(
            <div>
                {data.map((order) => (
                    <div key={order.ID}>
                      <br></br>
                      ID : {order.ID}
                      <br></br>
                      Email/Fax: <input defaultValue={order.cmt} placeholder="Sales Ack Email" id="salesAck" style={{width: "370px"}} />
                    </div>
                ))}
                <div>
                <br></br>
                <br></br>
                  <button onClick={onSubmit}>Update</button>
                </div> 
          </div>
        )
    }
    return (
        <h1>Something went wrong, please contact IT!</h1>
    )
}

export default FetchOrderDetails;

我怀疑问题可能是来自EmailFaxDetails.js页面,而试图通过ID,因为有2个ID的每个号码的用户搜索。我可能是错误的,如果有人可以找到错误,并帮助使它正确,我真的很感激。

wh6knrhe

wh6knrhe1#

我认为这里的问题是setId(response.data)
您只需要为orderid检索id和same

相关问题