如何从axios API调用获取响应的ID-使用React Native的Axios

时间:2018-08-28 17:51:13

标签: javascript reactjs api react-native axios

我正在使用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(响应):

{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

1 个答案:

答案 0 :(得分:0)

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

SELECT SCOPE_IDENTITY()

这将为您提供新记录的ID。

更新的查询示例

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

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

希望这会有所帮助:-)