【发布时间】:2018-10-11 23:15:35
【问题描述】:
我正在玩 React(我是新手)并尝试向我的 Rails API(在 localhost atm 上)发出发布请求。我还编写了 post 函数来 console.log 我的响应,我始终收到 200 响应,确认对象已在我的 API 中成功创建。但是,我想通过我的http响应来确认是否传递了正确的参数,并且似乎没有正文。不确定我是否在我的发布请求中丢失了,或者我在发出发布请求后是否错误地更新了我的状态。
我的反应组件
import React, { Component } from 'react';
import axios from 'axios'
import update from 'immutability-helper'
import BusinessForm from './businessForm'
const API = 'http://localhost:3001/api/v1/businesses/'
class NewBusinesses extends Component {
state = {
businesses: [],
editID: null
}
check = () => {
console.log(this.state.businesses)
}
addNew = () => {
axios.post(
API,
{
business:
{ name: 'NEW BUSINESS',
address: '',
city: '',
zip: '',
wifi: '',
phone: '',
bathroom: ''
}
}
)
.then(response => {
console.log(response)
const businesses = update(this.state.businesses, {
$splice: [[0,0,response.data]]
})
this.setState({businesses: businesses,
editID: response.data.id})
})
.catch(error => console.log(error))
}
我onClick函数后的控制台(console.log(response))
{data: "", status: 200, statusText: "OK", headers: {…}, config: {…}, …}
config:{adapter: ƒ, transformRequest: {…}, transformResponse: {…}, timeout: 0, xsrfCookieName: "XSRF-TOKEN", …}
data:""
headers:
{content-type: "text/html", cache-control: "no-cache"}
request
:
XMLHttpRequest {onreadystatechange: ƒ, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}
status:200
statusText:"OK"
__proto__:Object
【问题讨论】:
-
在你的 API 中的 rails 控制器是否在向其发送 post 请求后返回数据?
-
@aaron.v 感谢您的快速帮助!
标签: ruby-on-rails reactjs api redux axios