首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >获取http://localhost:3000/api/users/:userId 400 (错误请求),Axios React

获取http://localhost:3000/api/users/:userId 400 (错误请求),Axios React
EN

Stack Overflow用户
提问于 2021-01-22 04:12:41
回答 1查看 539关注 0票数 1

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

组件

代码语言:javascript
运行
复制
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);

控制器

代码语言:javascript
运行
复制
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

代码语言:javascript
运行
复制
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!"))

模式

代码语言:javascript
运行
复制
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);
代码语言:javascript
运行
复制
EN

回答 1

Stack Overflow用户

发布于 2021-01-22 11:36:54

您需要在来自客户端的GET请求中包括服务器端localhost端点。

代码语言:javascript
运行
复制
 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中使用代理,如下所示:

代码语言:javascript
运行
复制
"proxy":"http://localhost:5000"

这将允许您像在GET请求实现中那样编写端点路径。

对于CORS错误,

npm install cors的身份在服务器端package.json中安装CORS

然后将CORS作为const cors = require('cors');导入到您的server.js

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65835063

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档