繁体   English   中英

Postman 获取请求有效,但在浏览器中无效 - react/mongoose/express

[英]Postman Get request works but not in browser- react/mongoose/express

我知道还有很多其他“postman 中的作品,而不是浏览器中的作品”帖子,但我已经阅读了它们,找不到任何可以说明我在这里没有发现的内容的内容。 其中大多数与代理问题有关,但我没有设置任何代理。

我最近从使用 pymongo 后端更改为 mongoose/express。 我的 find() 适用于在浏览器端获取所有客户端就好了,但是 findOne() get 回来未定义(我收到了一个意外的令牌 JSON 错误,但虽然我不知道实际修复了什么但已解决),但是在 Postman 中,它带来了我正在寻找的东西。 我假设它很简单,但我似乎无法发现它。

后端- index.js

const express = require("express")
const mongoose = require("mongoose")
const cors = require('cors')
const clientRoutes = require("./routes/clientRoutes")
const contractRoutes = require("./routes/contractRoutes")
const bodyParser = require('body-parser');

mongoose
    .connect("MONGODB URL", { useNewUrlParser: true })
    .then(() => {
        const app = express()
        app.use(express.json())
        app.use(cors())
        app.use(bodyParser.json());
        app.use("/api", clientRoutes)
        app.use("/api", contractRoutes)

        app.listen(5000, () => {
        console.log("Server has started")   
        })

})

架构

const mongoose = require("mongoose")

const schema = mongoose.Schema({
    clientId: Number,
    firstName: String,
    lastName: String,
    phone: String,
    contracts: [{
        contractId: Number,
        authNumber: String,
        contType: String,
        contHours: Number,
        contStartDate: Date,
        contEndDate: Date
    }],

})

module.exports = mongoose.model("Client", schema)

路线-

const express = require("express")
const Client = require("../models/Client.js")
const router = express.Router()


//Client routes
router.get("/clients", async (req, res) => {
    const clients = await Client.find()
    res.send(clients)
})

router.get("/clients/:clientId", async (req, res) => {
   try {
    const client = await Client.findOne({ clientId: req.params.clientId })
    res.send(client)
   } catch {
       res.status(404)
       res.send({ error: "Client not found"})
   }
})

React 前端组件发出请求-

import React from 'react';
import PropTypes from 'prop-types';
import { withRouter } from 'react-router-dom';
import ChartNav from './ChartNav';
import ClientContext from './ClientContext';




class ClientChart extends React.Component {

    

    static get propTypes() {
        return {
            match: PropTypes.any,
            clientId: PropTypes.any
        }
    }

    constructor (props){
        
        super(props);
        this.state = {
            clientId: this.props.match.params.clientId,
            client: {},
            isLoading: true,
            errors: null
        };
        console.log(this.state.clientId)
        
    }
    
    
    componentDidMount(){
        
        fetch(`http://localhost:5000/api/clients/${this.state.clientId}`)
            .then(res => res.json())      
            .then(
                result => {
                    let client = JSON.parse(result.data);

                    this.setState({ 
                        isLoading: false,
                        client: client,
                        
                     });
              }, [])
              .catch(error => this.setState({
                error: error.message,
                isLoading: false,
              }));
              
    }

控制台和响应

404

XHR GET http://localhost:5000/api/clients/undefined

错误“找不到客户端”

因此,在尝试追踪它时,我将 clientId 切换回 id (我之前一直在使用,并将 1 个客户端的数据库中的 prop 更改回 id 以进行测试),并在初始响应后调用 console.log fetch 显示了通过的数据。 当我从该初始响应中设置状态时,所有道具都填充在它们应该填充的位置。 在将 id 恢复为 clientId 并更改路由以及使用带有 clientId 字段的客户端等时,没有任何效果。 因此,如果有人知道为什么 React 对 id 而不是 clientId 作为标识符感到满意,请告诉我。 更奇怪的是,它能够调用我仍然用 clientId 列出的所有其他客户端,并且路由是由 clientId 调用的,而不是 id ......所以我完全不知道引擎盖下发生的事情。

下面是正在工作的 get 调用(我也曾在一次尝试追踪它并将其留在那里的时候加入 axios,但最初它没有任何区别)。

axios.get(`http://localhost:5000/api/clients/${this.state.id}`)
            .then((response) => {
                const data = response.data;
                 console.log(response.data);
                 this.setState({
                     client: data,
                    isLoading: false,
                    });
            }, [])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM