簡體   English   中英

無法從反應表單將數據發布到我的 API

[英]Unable to post data to my API from a react form

我想從這個表單向我的 API 發布數據。 但不幸的是,有一個服務器錯誤。 有人能告訴我到底是什么問題嗎? (我觀察到沒有為對象生成 id)這是單擊提交按鈕后我在控制台中遇到的錯誤:

POST https://alert-amigo-api.herokuapp.com/products 500(內部服務器錯誤)響應 {type: "cors", url: " https://alert-amigo-api.herokuapp.com/products ",重定向:false,狀態:500,ok:false,...} 類型:“cors” url:“ https://alert-amigo-api.herokuapp.com/products ” 重定向:false 狀態:500 ok:false statusText:“內部服務器錯誤”

這是我的代碼:

import React, { Component } from "react";
import { Link } from 'react-router-dom';
import { Form, FormControl, FormCheck } from 'react-bootstrap';
import { FormGroup, ControlLabel, Row, Button, Checkbox, Radio, HelpBlock } from "react-bootstrap";

function FieldGroup({ id, label, help, ...props }) {
return (
    <FormGroup controlId={id}>
    <ControlLabel>{label}</ControlLabel>
    <FormControl {...props} />
    {help && <HelpBlock>{help}</HelpBlock>}
    </FormGroup>
  );
}

class Typography extends Component {
  constructor() {
    super();

    this.state = {
      productName: '',
      productPrice: '',
      productCategory: '',
      productBrand: '',
      countryOfOrigin: '',
      riskType: '',
      alertSubmittedBy: '',
      yourCity: '',
      yourAddress: '',
      productImage: '',
      description: ''
    };
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  changeHandler = e => {
    this.setState({[e.target.id]: e.target.value})
  }

  handleSubmit(e) {
      e.preventDefault();

      console.log('The form was submitted with the following data:');
      console.log(this.state);
    fetch('https://alert-amigo-api.herokuapp.com/products',{
        method: 'POST',
        headers: {
            Accept: 'application/json',
                    'Content-Type': 'application/json',
        },
        body: JSON.stringify(this.state)
    }).then(response => {
            console.log(response)
        })
        .catch(error =>{
            console.log(error)
        });

}

  render() {
    return (
      <div className="typoForm">
  <form onSubmit={this.handleSubmit}>
    <FieldGroup
      id="productName"
      name="productName"
      type="text"
      label="Product Name"
      placeholder=""
      value={this.state.productName}
      onChange={this.changeHandler}
    />
    <FieldGroup
      id="productPrice"
      name="productPrice"
      type="number"
      label="Product Price (in Euros)"
      placeholder=""
      value={this.state.productPrice}
      onChange={this.changeHandler}
    />
    <FormGroup controlId="productCategory" name="productCategory">
      <ControlLabel>Category</ControlLabel>
      <FormControl componentClass="select" name="productCategory" placeholder="select" onChange={this.changeHandler} value={this.state.selectValue}>
        <option value="select">select the category to which the product belongs to</option>
        <option value="electronics">Electronics</option>
        <option value="cosmetics">Cosmetics</option>
        <option value="apparels">Apparels</option>
        <option value="footwear">Footwear</option>
        <option value="accessories">Watches/Accessories</option>
        <option value="handbags">Handbags/Wallets</option>
        <option value="pharmaceuticals">Pharmaceuticals/Personal Care</option>
        <option value="Toys">Toys</option>
      </FormControl>
    </FormGroup>
    <FieldGroup
      id="productBrand"
      name="productBrand"
      type="text"
      label="Product Brand"
      placeholder=""
      value={this.state.productBrand}
      onChange={this.changeHandler}
    />
    <FieldGroup
      id="countryOfOrigin"
      name="countryOfOrigin"
      type="text"
      label="Country Of Origin"
      placeholder=""
      value={this.state.countryOfOrigin}
      onChange={this.changeHandler}
    />
    <FormGroup controlId="riskType" name="riskType">
      <ControlLabel>Risk Type</ControlLabel>
      <FormControl componentClass="select" placeholder="select" name="riskType" onChange={this.changeHandler} value={this.state.selectValue}>
        <option value="select">select the level of risk</option>
        <option value="high">high</option>
        <option value="medium">medium</option>
        <option value="low">low</option>
      </FormControl>
    </FormGroup>
    <FormGroup controlId="alertSubmittedBy" name="alertSubmittedBy">
      <ControlLabel>Alert Submitted By</ControlLabel>
      <FormControl componentClass="select" onChange={this.changeHandler} name="alertSubmittedBy" placeholder="select" value={this.state.selectValue}>
        <option value="select">select</option>
        <option value="producers">producers</option>
        <option value="consumers">consumers</option>
        <option value="distributors">distributors</option>
      </FormControl>
    </FormGroup>
    <FieldGroup
      id="yourCity"
      name="yourCity"
      type="text"
      label="Your City"
      placeholder=""
      value={this.state.yourCity}
      onChange={this.changeHandler}
    />
    <FormGroup controlId="yourAddress" name="yourAddress">
      <ControlLabel>Your Address</ControlLabel>
      <FormControl componentClass="textarea" name="yourAddress" onChange={this.changeHandler} value={this.state.value} placeholder="Enter your address here" />
    </FormGroup>
    <FieldGroup
      id="productImage"
      name="productImage"
      type="file"
      label="File"
      value={this.state.value}
      onChange={this.changeHandler}
      help="Upload an image of the product."
    />
    <FormGroup controlId="description" name="description">
      <ControlLabel>Please mention the defaults of the product</ControlLabel>
      <FormControl componentClass="textarea" name="description" onChange={this.changeHandler} value={this.state.value} placeholder="" />
    </FormGroup>

    <Button type="submit">Submit</Button>
  </form>
  </div>

    );
  }
}
export default Typography;

500 錯誤代碼是服務器端錯誤。 因此,您應該調試您的 API 代碼,而不是您的 React 代碼以找出問題的根源。

話雖如此,錯誤消息表示 CORS 錯誤。 如果您不熟悉跨域資源共享 (CORS) ,我建議您在繼續進行故障排除之前先閱讀並熟悉它。

此錯誤很可能是由於托管您的 reactjs 組件的域與托管您的 api 的域(alert-amigo-api.herokuapp.com)不同,並且 1) 該 API 未配置為跨域請求,或者 2) 它是為 CORS 配置的,但是您的 reactjs 客戶端沒有設置正確的標頭來啟用 CORS 所需的預檢請求。

請查看以下內容以獲取更多信息:
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
https://cors-anywhere.herokuapp.com/
https://medium.com/@dtkatz/3-ways-to-fix-the-cors-error-and-how-access-control-allow-origin-works-d97d55946d9
https://github.com/swagger-api/swagger-ui/blob/master/docs/usage/cors.md

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM