【问题标题】:Axios.post doen't work in react jsAxios.post 在反应 js 中不起作用
【发布时间】:2019-01-29 05:23:37
【问题描述】:

我在 react js 中使用 Axios 从 API(我使用 .NET WEB API 创建)获取数据 Axios.Get 非常适合我,现在我正在尝试使用 Axios.Post 通过我的 API (http://localhost:51492/api/experience) 在我的数据库中添加数据 但我在后端项目中遇到错误:

SqlException:INSERT 语句与 FOREIGN KEY 冲突 约束“FK_experiences_users_UserID”。冲突发生在 数据库“master”,表“dbo.users”,列“Id”。该声明有 被终止了。

当我在收到上一个错误后继续运行我的后端项目时出现此错误:(错误显示在谷歌开发工具中)

加载资源失败:服务器响应状态为 500 (内部服务器错误)配置文件:1 未能加载 http://localhost:51492/api/experience:没有 请求中存在“Access-Control-Allow-Origin”标头 资源。因此不允许使用原点“http://localhost:3000” 使用权。响应的 HTTP 状态代码为 500。

createError.js:16 Uncaught (in promise) 错误:网络错误 在 createError (createError.js:16) 在 XMLHttpRequest.handleError (xhr.js:87) createError@createError.js:16 handleError@xhr.js:87

这是我在 react js 中使用 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>
    )
  }
}

请问有人可以帮助我吗?提前谢谢你

【问题讨论】:

    标签: javascript reactjs post axios asp.net-core-webapi


    【解决方案1】:

    请确保您已在服务器端启用 CORS 以用于开发目的。

    试试这种方式设置header并发送post请求:

    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;
        });
    

    如果问题仍然存在,请告诉我!乐于助人

    【讨论】:

    • 非常感谢您让它工作,Cors 已经启用
    • 很高兴听到这个消息。
    • 我添加了标题(“Access-Control-Allow-Origin:*”);在 PHP 文件之上。它奏效了。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-06
      • 2020-09-04
      • 1970-01-01
      • 2021-06-27
      • 2021-09-04
      • 2021-12-30
      • 2018-04-01
      • 2019-02-25
      相关资源
      最近更新 更多