Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
376 views
in Technique[技术] by (71.8m points)

javascript - Axios - How to read JSON response?

Axios 0.17.1

.then(function (response) {
                console.log(response);
                //console.log(response.status);
                //It is an error -> SyntaxError: Unexpected token u in JSON at position 0 
                console.log(JSON.parse(response.data.error));
                console.log(response.data.error); //undefined.

The console.log of response is

{data: "{"error":"Name must be entered with more than one … NULL?
["isPipe":protected]=>? NULL? }?}?", status: 203, statusText: "Non-Authoritative Information", headers: {…}, config: {…}, …} config : {adapter: ?, transformRequest: {…}, transformResponse: {…}, timeout: 0, xsrfCookieName: "XSRF-TOKEN", …} data : "{"error":"Name must be entered with more than one character."}object(SlimHttpResponse)#32 (5) {? ["status":protected]=>? int(200)? ["reasonPhrase":protected]=>? string(0) ""? ["protocolVersion":protected]=>? string(3) "1.1"? ["headers":protected]=>? object(SlimHttpHeaders)#33 (1) {?
["data":protected]=>? array(1) {? ["content-type"]=>?
array(2) {? ["value"]=>? array(1) {? [0]=>?
string(24) "text/html; charset=UTF-8"? }?
["originalKey"]=>? string(12) "Content-Type"? }? }? }? ["body":protected]=>? object(SlimHttpBody)#31 (7) {?
["stream":protected]=>? resource(59) of type (stream)?
["meta":protected]=>? NULL? ["readable":protected]=>? NULL?
["writable":protected]=>? NULL? ["seekable":protected]=>?
NULL? ["size":protected]=>? NULL? ["isPipe":protected]=>?
NULL? }?}?" headers : {content-type: "application/json;charset=utf-8"} request : XMLHttpRequest {onreadystatechange: ?, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …} status : 203 statusText : "Non-Authoritative Information" proto : Object

JSON.parse(response.data) as well as response.data.error -> Both are giving error. How can i read the data?

Slimframework 3.

$data = array('error' => 'Name must be entered with more than one character.');
        $newResponse = $response->withJson($data, 203);
        return $newResponse;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In Axios responses are already served as javascript object, no need to parse, simply get response and access data.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...