【问题标题】:Axios Post returning no data after 200 responseAxios Post 200 响应后不返回数据
【发布时间】: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


【解决方案1】:

没关系!这个问题出在 API 方面,不是因为我在 React 应用程序中所做的任何事情。我必须添加行

render json:@business

在我的 Rails API 中创建方法

【讨论】:

  • 不确定这是否适用于您,但您也可能需要为发布请求执行此操作。 axios.defaults.headers.common['X-CSRF-Token'] = yourCSRFTokenHere; axios.defaults.headers.common.Accept = 'application/json';
  • ^^ 好喊布兰登。如果您将 respond_to 与 js 格式一起使用,请务必正确接受标头。没有它,Rails 将以默认的html 格式响应。
猜你喜欢
  • 1970-01-01
  • 2019-06-20
  • 2022-01-11
  • 1970-01-01
  • 2019-06-10
  • 2018-12-03
  • 2022-09-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多