简体   繁体   中英

Axios.post doen't work in react js

i'm using Axios in react js to fetch data from API( which i created with .NET WEB API ) The Axios.Get worked perfectly for me , now i'm trying to use Axios.Post to Add Data In My DataBase Via My API ( http://localhost:51492/api/experience ) but i'm getting in the backend project an error :

SqlException : The INSERT statement conflicted with the FOREIGN KEY constraint "FK_experiences_users_UserID". The conflict occurred in database "master", table "dbo.users", column 'Id'. The statement has been terminated.

and this error appear when i continue running my backend project after getting the previous error : ( error shown in google dev tools )

Failed to load resource: the server responded with a status of 500 (Internal Server Error) profile:1 Failed to load http://localhost:51492/api/experience : No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ' http://localhost:3000 ' is therefore not allowed access. The response had HTTP status code 500.

createError.js:16 Uncaught (in promise) Error: Network Error at createError (createError.js:16) at XMLHttpRequest.handleError (xhr.js:87) createError @ createError.js:16 handleError @ xhr.js:87

this is my code in react js using axios.post :

import React from 'react';
import axios from 'axios';
 var nowDate = new Date();
export default class PersonList extends React.Component {
  state = {
    titre: '',
    contenu: ''
  }

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

  handleSubmit = event => {
    event.preventDefault();

    const exp = {
      titre: this.state.titre,
      contenu: this.state.contenu,
      datePub:  nowDate ,
      userID: 1
    };

    axios.post(`http://localhost:51492/api/experience`, { exp })
      .then(res => {
        console.log(res);
        console.log(res.data);
       })


  }

  render() {
    return (
      <div>
        <form onSubmit={this.handleSubmit}>
          <label>
            titre:
            <input type="text" name="titre" onChange={this.handleChange} />
          </label>
          <label>
            contenu:
            <input type="text" name="contenu" onChange={this.handleChange} />
          </label>

          <button type="submit">Add</button>
        </form>
      </div>
    )
  }
}

Please can someone help me ? thank u in advance

Please make sure you have enabled CORS on server side for development purpose.

Try this way to set header and send a post request:

const URL = `http://localhost:51492/api/experience`;

 return axios(URL, {
    method: 'POST',
    headers: {
      'content-type': 'application/json',
    },
    data: exp,
  })
    .then(response => response.data)
    .catch(error => {
      throw error;
    });

Let me know if the issue still persists ! Happy to help

您需要在服务器中启用CORS(它基本上允许每个XHR实例向其请求数据。有关如何在ASP.NET上启用CORS的在线资源很多。如果您不拥有服务器,请考虑使用fetch代替axios 。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM