【问题标题】:POST: 400 BAD REQUEST on REACT APP - using ExpressPOST:REACT APP 上的 400 BAD REQUEST - 使用 Express
【发布时间】:2023-03-13 22:56:02
【问题描述】:

我正在学习 React,而且我也是新手,所以我非常感谢您的帮助!所以我目前卡在我的 POST 请求上,我得到一个状态 400 = 我已经能够将我的数据存储在 JSON 对象中并获得正确的信息以显示在我的客户端。但是,我正在尝试发出 POST 请求来更新标题和描述,并将我的新视频添加到前端的列表中。这是我的代码

反应组件/AXIOS 请求

import React from 'react';
import upload from '../../assets/Images/Upload-video-preview.jpg';
import axios from 'axios';
import './Upload.scss';

class Upload extends React.Component {
   state = {
    title: '',
    description: ''
}

handleChange = event => {
    this.setState({title: event.target.value, description: event.target.value});
}

submitHandler = (event) => {
    console.log('FORM', event.target.title.value, event.target.description.value);
    event.preventDefault();
    axios.post('http://localhost:8080/videos/')
    .then(results => {
        console.log(results);
    })
 
}

render() {
    return(
        <section className="upload">
            <h1 className="upload-header">Upload Video </h1>
            <div className="upload-div">   
                <div className="upload-div__inner">
                    <h3 className="upload-div__inner--h3">Video Thumbnail</h3>
                    <img src={upload}  className="upload-div__inner--img"/>
                </div>
            <form className="upload-form" onSubmit={this.submitHandler}>
               <div className="upload-form--div">
                    <label className="upload-form--div-label">TITLE YOUR VIDEO</label>
                        <input type="text" name="title" className="upload-form--div-input" />
                    <label className="upload-form--div-label">ADD A VIDEO DESCRIPTION</label>
                    <input type="text" name="description" className="upload-form--div-input" />
                </div> 
                <button type="submit" className="comment__form--outer-button" >Cancel</button>
                <button type="submit" className="comment__form--outer-button" >Publish</button>
            </form>
            </div>
        </section>
    )

    }
}

导出默认上传;

服务器端代码:

const express = require('express');
const app = express();
const router = express.Router();
const { v4: uuidv4 } = require('uuid');
const videoList = require('../data/videoId.json');
const fs = require('fs');

app.use(express.json());

router.get('/', (req, res) => {
    res.status(200).json(videoList);

})
console.log(videoList);
router.get('/:id', (req, res) => {
    const search = videoList.find((video) => video.id == req.params.id);
    if (search) {
      res.status(200).json(search);
    } else {
     res.status(400).json({
      error: 'Video not found'
      });
    }
  });

  router.post('/', (req, res) => {
    console.log(req.params)
    if(req.headers["content-type"] && req.headers["content-type"]==="application/json"){
      if(req.body){
          let newVideo = {
              id: uuidv4(),
              title: req.body.title,
              description: req.body.description
          }

          videoList.push(newVideo)

          fs.writeFile('./videoId.json', JSON.stringify(videoList), (err) => {
              if(!err){
                  res.status(201).send(newVideo)
              } else {
                  res.status(400).send({
                      success: false,
                      message: `Unable to write to videoId.json: ${err}`
                  })
              }
          })
      } else {
          res.status(400).send({
              success: false,
              message: "Data malformed"
          })
      }
  } else {
      res.status(400).send({
          success: false,
          message: "Invalid content type"
      })
  }

  })

module.exports = router;

我的对象存在于一个名为 videoId.json 的文件中,这是它的一个 sn-p:

    [
{
    "id": "1af0jruup5gu",
    "title": "BMX Rampage: 2018 Highlights",
    "channel": "Red Cow",
    "image": "https://i.imgur.com/l2Xfgpl.jpg",
    "description": "On a gusty day in Southern Utah, a group of 25 daring mountain bikers             lew the doors off what is possible on two wheels, unleashing some of the biggest moments the sport has ever seen. While mother nature only allowed for one full run before the conditions made it impossible to ride, that was all that was needed for event veteran Kyle Strait, who won the event for the second time -- eight years after his first Red Cow Rampage title",
"views": "1,001,023",
"likes": "110,985",
"duration": "4:01",
"video": "https://project-2-api.herokuapp.com/stream",
"timestamp": 1545162149000,
"comments": [
    {
        "name": "Micheal Lyons",
        "comment": "They BLEW the ROOF off at their last show, once everyone started figuring out they were going. This is still simply the greatest opening of acconcert I have EVER witnessed.",
        "id": "1ab6d9f6-da38-456e-9b09-ab0acd9ce818",
        "likes": 0,
        "timestamp": 1545162149000
    },
    {
        "name": "Gary Wong",
        "comment": "Every time I see him shred I feel so motivated to get off my couch and hop on my board. He’s so talented! I wish I can ride like him one day so I can really enjoy myself!",
        "id": "cc6f173d-9e9d-4501-918d-bc11f15a8e14",
        "likes": 0,
        "timestamp": 1544595784046
    },
    {
        "name": "Theodore Duncan",
        "comment": "How can someone be so good!!! You can tell he lives for this and loves to do it every day. Everytime I see him I feel instantly happy! He’s definitely my favorite ever!",
        "id": "993f950f-df99-48e7-bd1e-d95003cc98f1",
        "likes": 0,
        "timestamp": 1542262984046
    }
]

} ]

【问题讨论】:

  • 检查您的浏览器控制台和网络,您很可能会看到与CORS 相关的问题。像"Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at $somesite" 这样的东西。这是因为您正在尝试访问相同的资源,您可以通过在 express 应用程序中添加 cors 标头/中间件配置来修复它。 npmjs.com/package/cors

标签: javascript reactjs express


【解决方案1】:

我想我想得太苦了,我稍微简化了我的代码 - 现在我只需要弄清楚下一步并传递我的值,以便它们在我发布请求时出现

  router.post('/', (req, res) => {
if(req.body) {
  videoList.push(req.body);
  res.status(201).json({
      success: true
  })
  } else {
     res.status(400).json({
          success: false,
          error: "Please provide a valid title!"
      })
  }

  })

【讨论】:

    猜你喜欢
    • 2020-03-23
    • 2019-02-24
    • 1970-01-01
    • 1970-01-01
    • 2017-11-30
    • 2011-08-31
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    相关资源
    最近更新 更多