微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

GET http://localhost:3000/api/users/:userId 400错误请求,Axios React

如何解决GET http://localhost:3000/api/users/:userId 400错误请求,Axios React

我正在处理一个 MERN 堆栈,并且正在尝试在其自己的页面显示单个用户的数据。该路由在 Postman 的服务器端工作,我可以通过 Id 获取用户。但是在客户端,当我尝试从该路由中使用 axios 获取用户信息时,我收到了 400 错误的请求。它们可能是我的任何端点的问题吗?

What localhost shows in my console

Error in the console

组件

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('/*',res) => {
//     res.sendFile(`${__dirname}/client/build/index.html`)
// })
// app.get('/*',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,isDone: false,isApproved: false
})

const MeetupSchema = new Schema({
    name: String,location: String,attended: false
})
const UserSchema = new Schema({
    name: {
      type: String,required: true
    },email: {
      type: String,password: {
      type: String,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);

解决方法

您需要在来自客户端的 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 错误,

在服务器端 package.json 中将 CORS 安装为 npm install cors

然后将 CORS 作为 const cors = require('cors');

导入您的 server.js

然后使用 CORS 作为中间件 app.use(cors());

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。