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



我知道还有很多其他的"在邮递员中工作而不是在浏览器中工作";帖子,但我已经通读了一遍,找不到任何东西来指导我在这里没有学到的东西。大多数都与代理问题有关,但我没有设置任何代理。

我最近从使用pymongo后端改为使用mongose/express。我的find((适用于浏览器端的get-all客户端,但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获取http://localhost:5000/api/clients/undefined

错误";客户端未找到";

因此,在试图跟踪它时,我将clientId切换回id(我以前一直在使用它,并将DB中的1个客户端的道具更改回id以进行测试(,并在fetch的初始响应显示数据通过后调用console.log。当我从最初的响应中设置State时,所有道具都会填充到它们应该填充的位置。在将id恢复为clientId并更改路由,以及使用带有clientId字段的客户端等过程中,一切都无法恢复。因此,如果有人知道为什么React对id而不是clientId作为标识符感到满意,请告诉我。更奇怪的是,它可以用clientId呼叫我列出的所有其他客户,而路由是用clientId而不是id呼叫的……所以我完全不知道引擎盖下发生了什么。

下面是正在工作的get call(我也曾在试图追踪它的过程中加入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,
});
}, [])

最新更新