Axios.Post doen‘t在Reaction js中工作 [英] Axios.post doen't work in react js

查看:21
本文介绍了Axios.Post doen‘t在Reaction js中工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

SqlException语句:INSERT语句与外键冲突 约束"FK_Experience_User_UserID"。冲突发生在 数据库"master",表"dbo.user",列"ID"。这份声明有 已终止。

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

加载资源失败:服务器响应状态为500 (内部服务器错误)配置文件:%1无法加载 http://localhost:51492/api/experience:否 "Access-Control-Allow-Origin"标头位于请求的 资源。因此,不允许原始地址‘http://localhost:3000’ 进入。响应的HTTP状态代码为500。

CreateError.js:16未捕获(承诺中)错误:网络错误 在createError(createError.js:16) At XMLHttpRequest.handleError(xhr.js:87)createError@createError.js:16 handleError@xhr.js:87

这是我使用axios.post:

在Reaction js中编写的代码
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>
    )
  }
}

请帮帮我好吗?预先感谢您

推荐答案

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

尝试以此方式设置标头并发送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;
    });

如果问题仍然存在,请让我知道!乐于助人

这篇关于Axios.Post doen‘t在Reaction js中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆