简体   繁体   English

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

[英]how to get the id of a response from an axios API call — Axios with React Native

I'm using axios to make a POST request to post information and send it to the Database. 我正在使用axios发出POST请求,以发布信息并将其发送到数据库。 After that, I declare .then to get the response of the POST request. 之后,我声明.then以获得POST请求的响应。 I want to get the id of the record I just created. 我想获取刚刚创建的记录的ID。 So I did response.config.data.id but it didn't work. 所以我做了response.config.data.id,但是没有用。 So I was wondering what should I call exactly to get the ID of the new record I just POSTED? 所以我想知道我应该确切调用什么来获取刚发布的新记录的ID?

This is my code: 这是我的代码:

 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' } }); 

This is my console.log(response): 这是我的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 

UPDATE TO THE QUESTION I ASKED 我问的问题的更新

The backend I make the POST request to is a rails backend. 我发出POST请求的后端是Rails后端。 Below is the create method inside my address_controller. 下面是我的address_controller内部的create方法。 I return Address.last.id but nothing gets returned in my console.log(response). 我返回了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 

I've recently had the same issue. 我最近有同样的问题。 I had to update the database query. 我不得不更新数据库查询。 I'm using stored procedures within MS SQL . 我在MS SQL中使用存储过程。 If you are using SQL, At the end of the query add: 如果使用的是SQL,请在查询末尾添加:

SELECT SCOPE_IDENTITY()

This will give you the Id of the new record back. 这将为您提供新记录的ID。

Updated query example 更新的查询示例

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

The above example will insert a record, then once complete will return the ID of the rows affected. 上面的示例将插入一条记录,然后完成后将返回受影响的行的ID。

Hope this helps :-) 希望这可以帮助 :-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM