【问题标题】:how to get the id of a response from an axios API call -- Axios with React Native如何从 axios API 调用中获取响应的 id -- Axios with React Native
【发布时间】:2018-08-28 17:51:13
【问题描述】:

我正在使用 axios 发出 POST 请求以发布信息并将其发送到数据库。之后,我声明 .then 以获取 POST 请求的响应。我想获取我刚刚创建的记录的 id。所以我做了 response.config.data.id 但它没有用。所以我想知道我应该调用什么来获取我刚刚发布的新记录的 ID?

这是我的代码:

import React, { Component } from 'react';
import { View, Text, StyleSheet, TextInput, Button } from 'react-native';
import axios from 'axios';

class RegistrationForm extends Component {
	constructor(props) {
		super(props);
		this.state = {
			streetname: '',
			zipcode: '',
			city: '',
			country: ''
		};
	}

	onSubmit = () => {
		const { streetname, zipcode, city, country } = this.state;
		axios
			.post('http://localhost:3000/addresses', {
				address: {
					streetname,
					zipcode,
					city,
					country
				}
			})
			.then(response => {
				console.log(response.config.data.id);
			});
	};

	render() {
		return (
			<View style={styles.container}>
				<TextInput
					style={{ height: 40, width: 80, borderColor: 'black', borderWidth: 2 }}
					onChangeText={streetname => this.setState({ streetname })}
					value={this.state.streetname}
				/>
				<TextInput
					style={{ height: 40, width: 80, borderColor: 'black', borderWidth: 2 }}
					onChangeText={zipcode => this.setState({ zipcode })}
					value={this.state.zipcode}
				/>
				<TextInput
					style={{ height: 40, width: 80, borderColor: 'black', borderWidth: 2 }}
					onChangeText={city => this.setState({ city })}
					value={this.state.city}
				/>
				<TextInput
					style={{ height: 40, width: 80, borderColor: 'black', borderWidth: 2 }}
					onChangeText={country => this.setState({ country })}
					value={this.state.country}
				/>
				<Button onPress={() => this.onSubmit()} title="Submit" color="#00ff00" />
			</View>
		);
	}
}


export default RegistrationForm;

const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: '#fff',
		alignItems: 'center',
		justifyContent: 'center'
	}
});

这是我的 console.log(response):

{data: {…}, status: 201, statusText: undefined, headers: {…}, config: {…}, …}
config
:
adapter
:
ƒ xhrAdapter(config)
data
:
"{"address":{"streetname":"Downtowb","zipcode":"1882RD","city":"Cairo","country":"Egypt"}}"
headers
:
Accept
:
"application/json, text/plain, */*"
Content-Type
:
"application/json;charset=utf-8"
__proto__
:
Object
maxContentLength
:
-1
method
:
"post"
timeout
:
0
transformRequest
:
0
:
ƒ transformRequest(data, headers)
__proto__
:
Object
transformResponse
:
0
:
ƒ transformResponse(data)
__proto__
:
Object
url
:
"http://localhost:3000/addresses"
validateStatus
:
ƒ validateStatus(status)
xsrfCookieName
:
"XSRF-TOKEN"
xsrfHeaderName
:
"X-XSRF-TOKEN"
__proto__
:
Object
data
:
status
:
"address created successfully"
__proto__
:
constructor
:
ƒ Object()
hasOwnProperty
:
ƒ hasOwnProperty()
isPrototypeOf
:
ƒ isPrototypeOf()
propertyIsEnumerable
:
ƒ propertyIsEnumerable()
toLocaleString
:
ƒ toLocaleString()
toString
:
ƒ toString()
valueOf
:
ƒ valueOf()
__defineGetter__
:
ƒ __defineGetter__()
__defineSetter__
:
ƒ __defineSetter__()
__lookupGetter__
:
ƒ __lookupGetter__()
__lookupSetter__
:
ƒ __lookupSetter__()
get __proto__
:
ƒ __proto__()
set __proto__
:
ƒ __proto__()
headers
:
cache-control
:
"max-age=0, private, must-revalidate"
content-type
:
"application/json; charset=utf-8"
etag
:
"W/"0783f7a5f6931c50f5c5803429269854""
referrer-policy
:
"strict-origin-when-cross-origin"
transfer-encoding
:
"Identity"
x-content-type-options
:
"nosniff"
x-download-options
:
"noopen"
x-frame-options
:
"SAMEORIGIN"
x-permitted-cross-domain-policies
:
"none"
x-request-id
:
"f7ab51f0-d6c8-4043-aefa-f5f420f059cb"
x-runtime
:
"0.071757"
x-xss-protection
:
"1; mode=block"
__proto__
:
Object
request
:
XMLHttpRequest
DONE
:
4
HEADERS_RECEIVED
:
2
LOADING
:
3
OPENED
:
1
UNSENT
:
0
onabort
:
(...)
onerror
:
(...)
onload
:
(...)
onloadend
:
(...)
onloadstart
:
(...)
onprogress
:
(...)
onreadystatechange
:
(...)
ontimeout
:
(...)
readyState
:
4
responseHeaders
:
{X-Permitted-Cross-Domain-Policies: "none", X-XSS-Protection: "1; mode=block", Etag: "W/"0783f7a5f6931c50f5c5803429269854"", Transfer-Encoding: "Identity", X-Request-Id: "f7ab51f0-d6c8-4043-aefa-f5f420f059cb", …}
responseURL
:
"http://localhost:3000/addresses"
status
:
201
timeout
:
0
upload
:
XMLHttpRequestEventTarget {Symbol(listeners): {…}}
withCredentials
:
true
_aborted
:
false
_cachedResponse
:
undefined
_hasError
:
false
_headers
:
{}
_incrementalEvents
:
false
_lowerCaseResponseHeaders
:
{x-permitted-cross-domain-policies: "none", x-xss-protection: "1; mode=block", etag: "W/"0783f7a5f6931c50f5c5803429269854"", transfer-encoding: "Identity", x-request-id: "f7ab51f0-d6c8-4043-aefa-f5f420f059cb", …}
_method
:
"POST"
_requestId
:
null
_response
:
"{"status":"address created successfully"}"
_responseType
:
""
_sent
:
true
_subscriptions
:
[]
_timedOut
:
false
_trackingName
:
"unknown"
_url
:
"http://localhost:3000/addresses"
response
:
(...)
responseText
:
(...)
responseType
:
(...)
Symbol(listeners)
:
{readystatechange: {…}, error: {…}, timeout: {…}}
__proto__
:
EventTarget
onabort
:
(...)
onerror
:
(...)
onload
:
(...)
onloadend
:
(...)
onloadstart
:
(...)
onprogress
:
(...)
onreadystatechange
:
(...)
ontimeout
:
(...)
abort
:
ƒ abort()
addEventListener
:
ƒ addEventListener(type, listener)
constructor
:
ƒ XMLHttpRequest()
getAllResponseHeaders
:
ƒ getAllResponseHeaders()
getResponseHeader
:
ƒ getResponseHeader(header)
open
:
ƒ open(method, url, async)
response
:
(...)
responseText
:
(...)
responseType
:
(...)
send
:
ƒ send(data)
setReadyState
:
ƒ setReadyState(newState)
setRequestHeader
:
ƒ setRequestHeader(header, value)
setResponseHeaders
:
ƒ setResponseHeaders(responseHeaders)
setTrackingName
:
ƒ setTrackingName(trackingName)
__didCompleteResponse
:
ƒ __didCompleteResponse(requestId, error, timeOutError)
__didCreateRequest
:
ƒ __didCreateRequest(requestId)
__didReceiveData
:
ƒ __didReceiveData(requestId, response)
__didReceiveDataProgress
:
ƒ __didReceiveDataProgress(requestId, loaded, total)
__didReceiveIncrementalData
:
ƒ __didReceiveIncrementalData(requestId, responseText, progress, total)
__didReceiveResponse
:
ƒ __didReceiveResponse(requestId, status, responseHeaders, responseURL)
__didUploadProgress
:
ƒ __didUploadProgress(requestId, progress, total)
_clearSubscriptions
:
ƒ _clearSubscriptions()
_reset
:
ƒ _reset()
get response
:
ƒ ()
get responseText
:
ƒ ()
get responseType
:
ƒ ()
set responseType
:
ƒ (responseType)
__proto__
:
EventTarget
status
:
201
statusText
:
undefined
__proto__
:
Object

更新我提出的问题

我发出 POST 请求的后端是 rails 后端。下面是我的 address_controller 中的 create 方法。我返回 Address.last.id 但在我的 console.log(response) 中没有返回任何内容。

class AddressesController < ActionController::API
    
    def show
        address = Address.find(params[:id])
    end 

    def create
        address = Address.new(address_params)
      
        if address.save
          render json: {status: 'address created successfully'}, status: :created
          return Address.last.id
        else
          render json: { errors: address.errors.full_messages }, status: :bad_request
        end 
    end 
    
    def address_params
        params.require(:address).permit(:streetname, :zipcode, :city, :country)
    end
  
end

【问题讨论】:

  • response.data 为什么要做response.config?
  • 好的,所以它的'response.data.id'?
  • 如果您不提供返回数据的示例,您的问题不是很清楚。制作一个 console.log(response),复制并粘贴整个返回的数据并更新您的问题。
  • 也许可以发布 console.log(response) 的输出,看看里面的数据是如何构成的
  • @davidbucka 我编辑了我的问题以获得console.log(响应)。我找不到我刚刚创建的记录的 ID。我一直在查看整个日志,但没有指示 ID。这就是为什么我首先发布问题的原因。任何帮助将不胜感激。

标签: javascript reactjs api react-native axios


【解决方案1】:

我最近遇到了同样的问题。我不得不更新数据库查询。我在 MS SQL 中使用存储过程。如果您使用的是 SQL,请在查询末尾添加:

SELECT SCOPE_IDENTITY()

这将为您返回新记录的 ID。

更新的查询示例

INSERT INTO tbl (value1, value2) VALUES (A, B)
SELECT SCOPE_IDENTITY()

上面的示例将插入一条记录,然后一旦完成将返回受影响行的 ID。

希望这会有所帮助:-)

【讨论】:

  • 嗨@LukeWalker96,感谢分享。我正在使用 SQL 是的。我实际上是从我使用 rails 构建的一个小型 rest api 中获取数据的。如果我使用 Rails 和活动记录,我应该在哪里添加您共享的 sql 查询?再次感谢分享!
  • 没问题。直接在查询结束时。我将更新我的答案以包含一个适当的示例。假设您构建 sql 查询有问题,请在 Insert 查询之后直接添加 SELECT SCOPE_IDENTITY()。
  • 嗨@LukeWalker96 构造我的sql 查询有问题.. 我正在使用带有rails 的ActiveRecord 来做到这一点。你知道有机会从我的 Rails 控制器返回 id 吗?我做了 Address.last.id 但它没有返回任何东西......
  • 您能否更新您的帖子以包含您使用的查询?如果可以的话,我可能更容易从这里解释。
  • 尝试在倒数第二个end之后调用Address.id
猜你喜欢
  • 2023-04-10
  • 1970-01-01
  • 2020-08-10
  • 1970-01-01
  • 1970-01-01
  • 2021-07-27
  • 1970-01-01
  • 1970-01-01
  • 2017-07-18
相关资源
最近更新 更多