简体   繁体   English

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

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

I know there are a lot of other "works in postman and not in browser" posts, but I've read through them and cannot find anything to give direction on what I'm not catching here.我知道还有很多其他“postman 中的作品,而不是浏览器中的作品”帖子,但我已经阅读了它们,找不到任何可以说明我在这里没有发现的内容的内容。 Most of those had to do with proxy issues, but I dont have any proxy's set up.其中大多数与代理问题有关,但我没有设置任何代理。

I recently changed from using a pymongo backend to mongoose/express.我最近从使用 pymongo 后端更改为 mongoose/express。 My find() works for the get all clients just fine on the browser side, but the findOne() get comes back undefined (I was getting an unexpected token JSON error but that is resolved although I dont know what actually fixed it), yet in Postman it brings exactly what I'm looking for.我的 find() 适用于在浏览器端获取所有客户端就好了,但是 findOne() get 回来未定义(我收到了一个意外的令牌 JSON 错误,但虽然我不知道实际修复了什么但已解决),但是在 Postman 中,它带来了我正在寻找的东西。 I'm assuming its something simple, but I can't seem to spot it.我假设它很简单,但我似乎无法发现它。

Backend- index.js后端- 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")   
        })

})

Schema架构

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)

routes-路线-

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 frontend component making the request- 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,
              }));
              
    }

console and response控制台和响应

404 404

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

error "Client not found"错误“找不到客户端”

So in trying to track it down, I switched clientId back to id (which I had been using previously, and changed the prop in the DB for 1 client back to id to test), and calling console.log after the initial response from the fetch showed the data coming through.因此,在尝试追踪它时,我将 clientId 切换回 id (我之前一直在使用,并将 1 个客户端的数据库中的 prop 更改回 id 以进行测试),并在初始响应后调用 console.log fetch 显示了通过的数据。 When I setState from that initial response, all props populated where they should.当我从该初始响应中设置状态时,所有道具都填充在它们应该填充的位置。 In reverting the id back to clientId and changing the routes, and using a client with the clientId field, etc., nothing works again.在将 id 恢复为 clientId 并更改路由以及使用带有 clientId 字段的客户端等时,没有任何效果。 So if anyone knows why React is happy with id but not clientId as an identifier, please let me know.因此,如果有人知道为什么 React 对 id 而不是 clientId 作为标识符感到满意,请告诉我。 Even weirder is that its able to call all the other clients who I still have listed with clientId, and the routes are calling by clientId, not id... so Im at a total loss as to whats happening under the hood.更奇怪的是,它能够调用我仍然用 clientId 列出的所有其他客户端,并且路由是由 clientId 调用的,而不是 id ......所以我完全不知道引擎盖下发生的事情。

Below is the working get call (I also threw in axios at one point in trying to track it down and left it there, but initially it did not make any difference).下面是正在工作的 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.

相关问题 无法在Vuejs中获得mongoose查询的响应,但可以使用邮递员请求 - Unable to get the response of mongoose query inside Vuejs but works with postman request 浏览器获取请求 404'd 但适用于 Postman 应用程序 - Browser get request 404'd but works with Postman app 简单的 POST 请求在 Postman 中有效,但在浏览器中无效 - Simple POST request works in Postman but not in browser GET 请求从浏览器和邮递员工作,但在 React App 中从本地主机失败,端点是否必须添加访问控制允许来源? - GET request works from browser & Postman but fails from localhost in React App, does the endpoint necessarily have to add access-control-allow-origin? redash GET 请求适用于 POSTMAN 但不适用于 axios - redash GET request works on POSTMAN but not on axios Postman GET 请求有效,但 Ajax CORS 无效 - Postman GET request works but not Ajax CORS API适用于Postman,但不适用于浏览器 - API works in Postman, but not on a browser 为什么相同的POST请求在POSTMAN中起作用,但在浏览器AJAX中却不起作用(找不到404)? - Why the same POST request works in POSTMAN but not in browser AJAX (404 Not Found)? 获取在 Postman 上工作的请求,而不是在 React.js 中? - Get request working on Postman, but not in React.js? Axios 发布请求 React.js 时出现网络错误,但适用于 Postman - Axios Network error on post request React.js but works on Postman
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM