Axios.post doen#39;t work in react js(Axios.Post doen‘t在Reaction js中工作)
本文介绍了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中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:Axios.Post doen‘t在Reaction js中工作


基础教程推荐
猜你喜欢
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- 响应更改 div 大小保持纵横比 2022-01-01
- 在for循环中使用setTimeout 2022-01-01
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 悬停时滑动输入并停留几秒钟 2022-01-01
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- 动态更新多个选择框 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06