我正在处理一个MERN堆栈,并试图在其自己的页面上显示单个用户的数据。在Postman中,路由工作在服务器端,我可以通过Id获取用户。但是在客户端,当我试图使用axios从该路由获取用户信息时,收到了一个400错误的请求。它们会不会是我的任何端点的问题?
组件
import React, { Component } from 'react';
import { Link } from 'react-router-dom'
import axios from 'axios'
import PropTypes from "prop-types";
import { connect } from "react-redux";
import Navbar from '../layouts/navbar'
// import './userDashboard.css'
class userDashboard extends Component {
state = {
user: {}
}
getUser = () =>{
const userId = this.props.match.params.userId
axios.get('/api/users/' + userId ).then(res=>{
const user = res.data;
this.setState({
user
})
}).catch((err)=> console.log(err))
}
componentDidMount() {
this.getUser()
}
render() {
const { name } = this.state.user
return (
<div>
<Navbar />
<h1 className="title-text">Hello { name }</h1>
</div>
);
}
}
userDashboard.propTypes = {
// logoutUser: PropTypes.func.isRequired,
auth: PropTypes.object.isRequired,
};
const mapStateToProps = (state) => ({
auth: state.auth,
});
export default connect(mapStateToProps)(userDashboard);
控制器
router.get("/:userId", (req, res) => {
const { userId } = req.params;
if(!userId){
return res.status(400).json({message: "user id not found"})
}
if(!ObjectId.isValid(userId)){
return res.status(400).json({ message: "userId not valid"})
}
User.findById(userId,(err, user) => {
if(err) {
res.status(500);
console.log("errr 500")
} else {
if(!user)
res.status(400).json({message:"user not found"});
res.status(200).json({"user" : user})
}
})
})
server.js
const express = require("express");
const path = require('path');
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const passport = require("passport");
const app = express();
const users = require("./controllers/api/users")
app.use(
bodyParser.urlencoded({
extended: false
})
);
app.use(bodyParser.json());
app.use(express.static(`${__dirname}/client/build`));
// app.get('/*', (req, res) => {
// res.sendFile(`${__dirname}/client/build/index.html`)
// })
// app.get('/*', (req, res) => {
// res.sendFile(path.join(__dirname, '/../', 'build', 'index.html'));
// });
//DATA BASE CONFIGURATION
const dbkeys = require("./config/key").mongoURI;
mongoose.connect(
dbkeys,
{useNewUrlParser: true} )
.then(()=> console.log("database connection successful"))
.catch(err => console.log(err))
app.use(passport.initialize());
require("./config/passport")(passport);
app.use("/api/users", users);
// app.use("/api", users)
const port = 5000;
app.listen( port, () => console.log("server us up and running on port 5000!"))
模式
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const ClassworkSchema = new Schema({
name: String,
time: Date,
todo: String,
isDone: false
});
const OutcomesSchema = new Schema({
name: String,
time: Date,
todo: String,
isDone: false,
isApproved: false
})
const MeetupSchema = new Schema({
name: String,
time: Date,
location: String,
attended: false
})
const UserSchema = new Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true
},
password: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
},
classwork:{type: [ClassworkSchema], default: []},
outcomes: [OutcomesSchema],
meetups: [MeetupSchema],
});
// const User = mongoose.model('users', UserSchema);
// const Classwork = mongoose.model('Classwork', ClassworkSchema );
// module.exports = {
// User : User ,
// // Classwork : Classwork
// }
module.exports = mongoose.model("users", UserSchema);
发布于 2021-01-22 11:36:54
您需要在来自客户端的GET请求中包括服务器端localhost端点。
getUser = () =>{
const userId = this.props.match.params.id;
axios.get(`http://localhost:5000/api/users/${userId}`).then(res=>{
const user = res.data;
this.setState({
user
})
}).catch((err)=> console.log(err))
}
您正在请求来自服务器端的响应,因此需要包含响应应到达的正确路径。
您需要在从客户端发送到服务器端的所有请求中包含此路径。我建议在客户端package.json中使用代理,如下所示:
"proxy":"http://localhost:5000"
这将允许您像在GET请求实现中那样编写端点路径。
对于CORS错误,
以npm install cors
的身份在服务器端package.json中安装CORS
然后将CORS作为const cors = require('cors');
导入到您的server.js
然后使用CORS作为中间件app.use(cors());
https://stackoverflow.com/questions/65835063
复制相似问题