【问题标题】:axios request to node.js server not returning data对node.js服务器的axios请求不返回数据
【发布时间】:2020-06-26 06:51:47
【问题描述】:

编辑:只是我错过了一个错字。 我道歉。谢谢亚历山大

我的客户端没有收到响应数据。 但是,当我使用邮递员时,我得到了我需要的数据。 在控制台上,我收到以下错误。 知道为什么我会遇到这个问题吗?

Error: Request failed with status code 404
    at createError (createError.js:16)
    at settle (settle.js:17)
    at XMLHttpRequest.handleLoad (xhr.js:61) "error"

服务器端

const express = require("express");
const genreData = require("../data/genreData.json")
const fs = require ('fs')
const router = express.Router();

router.get("/", (_, res) => {
    res.json(genreData);
  });

router.get("/:id", (req, res) => {
    res.json(genreData.find(user => user.id == req.params.id))
})
 module.exports = router;

客户端

import React, { Component } from 'react'
import axios from 'axios'

export class Result extends Component {
    constructor (props) {
        super (props) 
            this.state = {
                user: {}
            }
    }
    componentDidMount () {
        axios.get(`http:/localhost:8001/genre/${this.props.match.params.id}`)
        .then(res => 
            this.setState({user: res.data}))
        .catch(error => {
            console.log(error, "error")
        })
    }
    render() {
        console.log(this.state.user)
        return (
            <div>
                <p>{this.state.user.id}</p>
            </div>
        )
    }
}

export default Result

邮递员获取http://localhost:8001/genre/52163492-5e66-4bbf-a3dc-2b8120e3afe8的请求

{
    "id": "52163492-5e66-4bbf-a3dc-2b8120e3afe8",
    "action": 3,
    "anime": 4,
    "children": 5,
    "comedy": 2,
    "documentary": 4,
    "drama": 5,
    "horror": 5,
    "musical": 5,
    "scifi": 5,
    "thriller": 5
}

【问题讨论】:

  • this.props.match.params.id 的值是多少?
  • http:/ 应该是 http:// 除非这是一个错字,您缺少一个 / 字符。

标签: node.js reactjs axios http-status-code-404 router


【解决方案1】:

console.log(this.props.match.params.id) 添加到componentDidMount() 以查看您的Id 是否正确

【讨论】:

    【解决方案2】:

    这与您正在运行的代码相同吗?我认为你有一个拼写错误

    axios.get(http:/localhost:8001/genre/${this.props.match.params.id})

    请在 http 后面加上 //。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-18
      • 2017-11-04
      • 2017-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-29
      • 1970-01-01
      相关资源
      最近更新 更多