Trying to refresh the access token I receive from Django every few seconds, however I am getting the error message
Request Method: POST Status Code: 400 Bad Request
I am sending my refresh token to this endpoint: "http://127.0.0.1:8000/api/token/refresh/"
This is my urls.py:
from rest_framework_simplejwt.views import (TokenObtainPairView, TokenRefreshView, TokenVerifyView)
router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
urlpatterns = [
path('', include(router.urls)),
path('admin/', admin.site.urls),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),
# path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
path('api/token/', CustomTokenObtainPairView.as_view(), name='token_obtain_pair'),
path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
path('api/token/verify/', TokenVerifyView.as_view(), name='token_verify'),
path('api/register', RegisterApi.as_view()),
]
This is how I am sending my refresh token:
let updateToken = async ()=> {
try {
let response = await axios.post('http://127.0.0.1:8000/api/token/refresh/',JSON.stringify(authTokens.refresh))
//update state with token
setAuthTokens(authTokens => ({
...response.data
}))
//update user state
const decoded = jwt_decode(response.data.access)
setUser(user => ({
...decoded
}))
//store tokens in localStorage
//we stringify because we can only store strings in localStorage
localStorage.setItem('authTokens',JSON.stringify(response.data))
}
catch(err) {
//if fail, something is wrong with refresh token
console.log(err.response)
}
}
This is the error I am getting:
config: {transitional: {…}, transformRequest: Array(1), transformResponse: Array(1), timeout: 0, adapter: ƒ, …}
data:
refresh: ['This field is required.']
[[Prototype]]: Object
headers:
content-length: "39"
content-type: "application/json"
[[Prototype]]: Object
request: XMLHttpRequest
onabort: ƒ handleAbort()
onerror: ƒ handleError()
onload: null
onloadend: ƒ onloadend()
onloadstart: null
onprogress: null
onreadystatechange: null
ontimeout: ƒ handleTimeout()
readyState: 4
response: "{\"refresh\":[\"This field is required.\"]}"
responseText: "{\"refresh\":[\"This field is required.\"]}"
responseType: ""
responseURL: "http://127.0.0.1:8000/api/token/refresh/"
responseXML: null
status: 400
statusText: "Bad Request"
timeout: 0
upload: XMLHttpRequestUpload {onloadstart: null, onprogress: null, onabort: null, onerror: null, onload: null, …}
withCredentials: false
[[Prototype]]: XMLHttpRequest
status: 400
statusText: "Bad Request"
[[Prototype]]: Object
This is what i have in authTokens:
{refresh: 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90e…9tIn0._aS9oDcj3Rfomodbs9qMEFmgEm4oEdOfSwGSJJKLWmg', access: 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90e…20ifQ.K1YCXWoMWF7o61fGAuVm-QoehB3-jA2A_dLZ4o4uYa8'}
The /api/token/refresh/ returns only the access token.
When you setAuthToken using the entire response data, you are most likely getting rid of the refresh token.
Now the next time you make the request, authTokens.refresh is undefined and thus does not get sent to the backend. The backend rightfully complains that it's a 400: Bad Request. refresh is a required field.
Modify your frontend code to only update the access token. When the refresh token expires, you need to call /api/token/ to login again.
Alternatively you can change the backend to rotate refresh tokens. This would send a new refresh token each time the access token is refreshed.
This is achieve by setting ROTATE_REFRESH_TOKENS = True in your settings.
If you want to make sure the old refresh token can no longer be used, you can blacklist them when rotated, by setting BLACKLIST_AFTER_ROTATION = True
Related
( https://ikgithub-finder.vercel.app/ )
this is a website im building to search github users following a react course.
im having a problem with the website not catching the response or some axios problem here.
im searching for github user and this is the response, which I didn't had in the building stage.
This is the code repo:
(https://github.com/IdanKfir/github-finder)
and this is what console.log gets from searching a user:
xhr.js:247 GET https://api.github.com/search/users?q=brad 401 asyncToGenerator.js:6 Uncaught (in promise) Ft {message: 'Request failed with status code 401', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …} code : "ERR_BAD_REQUEST" config : {transitional: {…}, adapter: Array(2), transformRequest: Array(1), transformResponse: Array(1), timeout: 0, …} message : "Request failed with status code 401" name : "AxiosError" request : XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …} response : {data: {…}, status: 401, statusText: '', headers: n, config: {…}, …} stack : "AxiosError: Request failed with status code 401\n at https://ikgithub-finder.vercel.app/static/js/main.e1a418f5.js:2:193546\n at XMLHttpRequest.d (https://ikgithub-finder.vercel.app/static/js/main.e1a418f5.js:2:193694)" [[Prototype]] : Error
I was trying to change the token I used from git, and the env file was uploaded so I had to delete.
to be honest I thought that was the problem so I reuploaded and again the same error.
Would love sending the whole codes instead of repo but it really lots of code, lucky me if you'll have the time to look for it anyways, thanks :)
I debug your code and find that inside your context/github.js your have a function of searchUser i.e :
export const searchUsers = async (text) => {
const params = new URLSearchParams({
q: text,
});
const response = await github.get(`/search/users?${params}`);
return response.data.items;
};
Here your are direactly getting the value of inside your text parameter so you don't need to user URLSearchParams just direactly pass it to your api call
export const searchUsers = async (text) => {
const response = await github.get(`/search/users?${text}`);
return response.data.items;
};
and if you want to use URLSearchParams you have to pass full url to the function that i see currently you are not doing .
Let me know if this works for you otherwise we will find another way :)
So, soon enough I found an answer to my question :D
To other people who have this problem maybe the solution will be the same;
So it was the token, but the problem was this:
Send Authorization in string
replace
{ headers: { Authorization: Bearer ${userInfo.token} } }
with { headers: { "Authorization": Bearer ${userInfo.token} } }
I have a problem with my code:
I'm using RecorderJS, and I'm trying to permise this to send sound to my back-end, but as streaming, not as complete recording.
I'm using HTML 5 and the last versions of python and flask.
I found where I had to put my code for doing that, but my problem is the communication beetween my back and my worker.
I tried to use XMLHttpRequest :
function send_buffer_to_transcription(sound_buffer) {
// no jquery in workers
var request = new XMLHttpRequest();
var url = "'/updateSound2'";
request.open("POST", url, true);
request.setRequestHeader("Content-Type", "application/json");
request.onreadystatechange = function () {
if (request.readyState === 4 && request.status === 200) {
console.log("son transmis");
}
};
var data = {
audioBuffer:JSON.stringify(Array(new Int16Array(sound_buffer)))
}
request.send(data);
}
But I had an issue with that :
Uncaught DOMException: Failed to execute 'open' on 'XMLHttpRequest': Invalid URL
at send_buffer_to_transcription (blob:http://127.0.0.1:5000/feb04c56-4e80-4418-885f-5f24bc7b9409:79:23)
at streaming_record (blob:http://127.0.0.1:5000/feb04c56-4e80-4418-885f-5f24bc7b9409:62:19)
at record (blob:http://127.0.0.1:5000/feb04c56-4e80-4418-885f-5f24bc7b9409:101:17)
at self.onmessage (blob:http://127.0.0.1:5000/feb04c56-4e80-4418-885f-5f24bc7b9409:27:25)
I tried with webSocket too :
let socket = new WebSocket("wss://127.0.0.1:5000/soudtesting");
socket.onerror = function (error) {
console.error(error);
}
function send_as_socket() {
socket.send('my message');
}
But here is the issue I've had :
7fdd8dd0-6354-467b-8b58-253c98412fdd:10 WebSocket connection to 'wss://127.0.0.1:5000/soudtesting' failed:
(nothing next)
the error looks :
isTrusted: true
bubbles: false
cancelBubble: false
cancelable: false
composed: false
currentTarget: WebSocket {url: 'wss://127.0.0.1:5000/soudtesting', readyState: 3, bufferedAmount: 0, onopen: null, onerror: ƒ, …}
defaultPrevented: false
eventPhase: 0
path: []
returnValue: true
srcElement: WebSocket {url: 'wss://127.0.0.1:5000/soudtesting', readyState: 3, bufferedAmount: 0, onopen: null, onerror: ƒ, …}
target: WebSocket {url: 'wss://127.0.0.1:5000/soudtesting', readyState: 3, bufferedAmount: 0, onopen: null, onerror: ƒ, …}
timeStamp: 0
type: "error"
[[Prototype]]: Event
Does someone has an explaination, and, if possible a solution please? Really needed.
=====
Oops, I forget this :
Here's the error which has occured in my back-end (I don't think this will be helpfull, but why not)
127.0.0.1 - - [06/Apr/2022 13:51:55] code 400, message Bad request version ('úú\x13\x01\x13\x02\x13\x03À+À/À,À0̨̩À\x13À\x14\x00\x9c\x00\x9d\x00/\x005\x01\x00\x01\x93êê\x00\x00\x00\x17\x00\x00ÿ\x01\x00\x01\x00\x00')
ax°×¥¡²DüöàO»Ëgïò&åf# úúÀ+À/À,À0̨̩ÀÀ / 5 êê ÿ " HTTPStatus.BAD_REQUEST -
127.0.0.1 - - [06/Apr/2022 13:51:55] code 400, message Bad request version ('êê\x13\x01\x13\x02\x13\x03À+À/À,À0̨̩À\x13À\x14\x00\x9c\x00\x9d\x00/\x005\x01\x00\x01\x93úú\x00\x00\x00\x17\x00\x00ÿ\x01\x00\x01\x00\x00')
èbÄÍdµÜQýH³¾²§¶E|}½eO ËX|Da¼j»-ÃñUxù©í弪v[` êêÀ+À/À,À0̨̩ÀÀ / 5 úú ÿ " HTTPStatus.BAD_REQUEST -
I made todo application, i could process GET,POST method in lambda function but i got error when invoke delete method.Here i want to delete data in dynamo db by making delete query from axios through lambda function
This is axios delete function,it send {"data": {"id":this.id}} to lambda
axios.delete('https://94sc9th9bi.execute-api.ap-northeast-1.amazonaws.com/prod/item',
{ "data": {"id":this.id}}).then(
res => {
console.log(res.data.id)
}).catch(err => {console.log(err)})
this.getalltask()
},
I have lambda api for delete
const AWS = require('aws-sdk')
const docClient = new AWS.DynamoDB.DocumentClient()
exports.handler = async (event) => {
console.log(event)
let body = JSON.parse(event.body);
const scanItemPayload = {
TableName: 'aws-training',
Key:{
id: body.data.id
}
}
console.log(body);
const dynamoDBResponse = await docClient.delete(scanItemPayload).promise()
console.log(dynamoDBResponse)
const response = {
body: JSON.stringify(dynamoDBResponse),
statusCode: 200,
headers: {
"Access-Control-Allow-Origin" : "*", // Required for CORS support to work
"Access-Control-Allow-Credentials" : true, // Required for cookies, authorization headers with HTTPS
},
};
return response;
};
i test lambda above with
{
"body": "{\"data\":{\"id\":\"1633613467228\"}}"
}
and i got statusCode 200 and no error and i check that the data is deleted in dynamo db
i have a DELETE method API that is related to the lambda function above, and i test delete method api above by giving query {item} => id=1633613467228 , this is the id i want to delete
but it gave me result
{
"message": "Internal server error"
}
with error log
Execution log for request f83e7e01-52ca-498d-b3e6-34d972510ad8
Fri Oct 08 15:50:00 UTC 2021 : Starting execution for request: f83e7e01-52ca-498d-b3e6-34d972510ad8
Fri Oct 08 15:50:00 UTC 2021 : HTTP Method: DELETE, Resource Path: /item
Fri Oct 08 15:50:00 UTC 2021 : Method request path: {}
Fri Oct 08 15:50:00 UTC 2021 : Method request query string: {id=1633613467228}
Fri Oct 08 15:50:00 UTC 2021 : Method request headers: {}
Fri Oct 08 15:50:00 UTC 2021 : Method request body before transformations:
Fri Oct 08 15:50:00 UTC 2021 : Endpoint request URI: https://lambda.ap-northeast-1.amazonaws.com/2015-03-31/functions/arn:aws:lambda:ap-northeast-1:184371581740:function:aws-training-20211006-p-delete/invocations
and i test with postman
https://94sc9th9bi.execute-api.ap-northeast-1.amazonaws.com/prod/item?id=1633613467228
i got error, it seem that the query ?id=1633613467228 is not work
i also test the application , i got CORRS/network error in console although i already set access control orign to *
Access to XMLHttpRequest at 'https://94sc9th9bi.execute-api.ap-northeast-1.amazonaws.com/prod/item?' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
index.vue?0f48:64 Error: Network Error
at createError (createError.js?2d83:16)
at XMLHttpRequest.handleError (xhr.js?b50d:117)
xhr.js?b50d:210 DELETE https://94sc9th9bi.execute-api.ap-northeast-1.amazonaws.com/prod/item? net::ERR_FAILED 502
so my questions are:
1.why delete method in api above result in internal server error and how can i test the method. i also got confused of the different between test in api gateway and test in lambda function. Is my test data wrong format?
in axios i have "data": {"id":this.id}}) , is
Key:{id: body.data.id} right way to get the data send by axios in aws lambda function?
this is the eror from amazon cloudwatch. it seems 'data' is null.
START RequestId: 8197a2bb-b045-438b-8b37-4467687006e3 Version: $LATEST
2021-10-09T06:28:31.894Z 8197a2bb-b045-438b-8b37-4467687006e3 INFO { key: { id: '1633613467228' } }
2021-10-09T06:28:31.927Z 8197a2bb-b045-438b-8b37-4467687006e3 ERROR Invoke Error
{
"errorType": "SyntaxError",
"errorMessage": "Unexpected token u in JSON at position 0",
"stack": [
"SyntaxError: Unexpected token u in JSON at position 0",
" at JSON.parse (<anonymous>)",
" at Runtime.exports.handler (/var/task/index.js:12:21)",
" at Runtime.handleOnce (/var/runtime/Runtime.js:66:25)"
]
}
END RequestId: 8197a2bb-b045-438b-8b37-4467687006e3
REPORT RequestId: 8197a2bb-b045-438b-8b37-4467687006e3 Duration: 56.29 ms Billed Duration: 57 ms Memory Size: 128 MB Max Memory Used: 72 MB Init Duration: 399.98 ms
START RequestId: ff096041-a1fb-4349-abbc-a5d422e034d6 Version: $LATEST
2021-10-09T06:29:04.648Z ff096041-a1fb-4349-abbc-a5d422e034d6 INFO {
resource: '/item',
path: '/item',
httpMethod: 'DELETE',
headers: null,
multiValueHeaders: null,
queryStringParameters: { id: '1633613467228' },
multiValueQueryStringParameters: { id: [ '1633613467228' ] },
pathParameters: null,
stageVariables: null,
requestContext: {
resourceId: '2gw7om',
resourcePath: '/item',
httpMethod: 'DELETE',
extendedRequestId: 'G7V7mFskNjMF-vg=',
requestTime: '09/Oct/2021:06:29:04 +0000',
path: '/item',
accountId: '184371581740',
protocol: 'HTTP/1.1',
stage: 'test-invoke-stage',
domainPrefix: 'testPrefix',
requestTimeEpoch: 1633760944483,
requestId: 'f7596258-871a-4b15-b62c-11d434e176b4',
identity: {
cognitoIdentityPoolId: null,
cognitoIdentityId: null,
apiKey: 'test-invoke-api-key',
principalOrgId: null,
cognitoAuthenticationType: null,
userArn: 'arn:aws:iam::184371581740:user/user07',
apiKeyId: 'test-invoke-api-key-id',
userAgent: 'aws-internal/3 aws-sdk-java/1.12.71 Linux/5.4.134-73.228.amzn2int.x86_64 OpenJDK_64-Bit_Server_VM/25.302-b08 java/1.8.0_302 vendor/Oracle_Corporation cfg/retry-mode/standard',
accountId: '184371581740',
caller: 'AIDASV3LHCMWIZKMZMLPE',
sourceIp: 'test-invoke-source-ip',
accessKey: 'ASIASV3LHCMWBJROEHQN',
cognitoAuthenticationProvider: null,
user: 'AIDASV3LHCMWIZKMZMLPE'
},
domainName: 'testPrefix.testDomainName',
apiId: '94sc9th9bi'
},
body: null,
isBase64Encoded: false
}
2021-10-09T06:29:04.667Z ff096041-a1fb-4349-abbc-a5d422e034d6 ERROR Invoke Error
{
"errorType": "TypeError",
"errorMessage": "Cannot read property 'data' of null",
"stack": [
"TypeError: Cannot read property 'data' of null",
" at Runtime.exports.handler (/var/task/index.js:16:19)",
" at Runtime.handleOnce (/var/runtime/Runtime.js:66:25)"
]
}
END RequestId: ff096041-a1fb-4349-abbc-a5d422e034d6
REPORT RequestId: ff096041-a1fb-4349-abbc-a5d422e034d6 Duration: 180.66 ms Billed Duration: 181 ms Memory Size: 128 MB Max Memory Used: 73 MB
START RequestId: 1adde91a-ce53-4d2f-8fa8-d296352fc689 Version: $LATEST
2021-10-09T06:30:01.788Z 1adde91a-ce53-4d2f-8fa8-d296352fc689 INFO { key: { id: '1633613467228' } }
2021-10-09T06:30:01.807Z 1adde91a-ce53-4d2f-8fa8-d296352fc689 ERROR Invoke Error
{
"errorType": "SyntaxError",
"errorMessage": "Unexpected token u in JSON at position 0",
"stack": [
"SyntaxError: Unexpected token u in JSON at position 0",
" at JSON.parse (<anonymous>)",
" at Runtime.exports.handler (/var/task/index.js:12:21)",
" at Runtime.handleOnce (/var/runtime/Runtime.js:66:25)"
]
}
intecept axios to see data
i test lambda function with body and got 200
test lambda with body
enter image description here
i test api gateway by add query for delete it gave internal server error
enter image description here
i tried to make request by using axios here, i want to delete task which name is 'aa' with id = 1633601975370
delete task name="aa"
as you can see, body with id is sent, but there is error when axios request delete api
error i got in console
error in console
amaxon cloudwatch log error
enter image description here
cloudwatch log error
I got a CORS error the in console even though I've already set Access-Control-Allow-Origin to *
The question is:
Are you trying to enable CORS for a Lambda proxy integration or a Lambda non-proxy integration?
Enabling CORS will differ based on the integration type.
First, refer to the Enable CORS on a resource using the API Gateway console section of the Amazon API Gateway developer guide as it includes images etc.
Follow the guide for proxy & non-proxy.
If it is a non-proxy integration, you're done.
If it's a proxy integration (which I don't think it is), your request will still fail - a DELETE request is classed as a complex request by the CORS specification.
This means that if you are making a call to this endpoint using a web app, you may have allowed all origins but you haven't specified which HTTP methods to allow (which the web app will request for in the form of a preflight request before the DELETE request).
So you'll need to also set the Access-Control-Allow-Methods header to * to allow HTTP DELETEin the response returned by your Lambda:
const response = {
body: JSON.stringify(dynamoDBResponse),
statusCode: 200,
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "*",
"Access-Control-Allow-Credentials": true
}
};
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(Slim\Http\Response)#32
(5) {↵ ["status":protected]=>↵ int(200)↵
["reasonPhrase":protected]=>↵ string(0) ""↵
["protocolVersion":protected]=>↵ string(3) "1.1"↵
["headers":protected]=>↵ object(Slim\Http\Headers)#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(Slim\Http\Body)#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;
In Axios responses are already served as javascript object, no need to parse, simply get response and access data.
Assuming the response from the server looks like this:
{"token": "1234567890"}
Then in Axios you can access it like this:
console.log( response.data.token )
As already written, Axios already returns JSON by default. Just use response.data as simple JS object.
However, following insight might help others: I had an issue that Axios returned the response as a string. When investigated I discovered that the server returned an invalid JSON (it was a static file server). When fixed the JSON format, Axios used JSON instead of string again.
you can simply get it as following,
ex:
{
"terms": {
"title": "usage",
"message": "this is the usage message"
}
}
when the response look like this,you can get it using "response.data",and so on....
.then(response =>
console.log( response.data.terms.message)
Cheers !
I had a similar format response as the one in console log and my issue was that my .json file wasn't properly formatted. I was missing a comma. Post your json file to have a look.
axios by defualt convert response to JSON, you must use response.data instead of response
export const addPosts = () => async (dispatch) => {
await axios('https://jsonplaceholder.typicode.com/todos/1')
.then(response => dispatch({type: postActionTypes.POSTS, payload: response.data}))}
For some reason, in my case the JSON was properly formatted but was returned as string anyway. With this workaround I solved the issue.
// ...
return await this.axios_instance.request<T>({
method,
url,
headers,
params,
transformResponse: (data) => JSON.parse(data), // <----------
data,
});
Simply put, I explicitly told to transform the response using JSON.parse. For some reason this worked, while other answers didn't.
This worked for me!! Hope it helps.
Here is sample code,
try {
const res = await axios.get("/end-point");
console.log("JSON data from API ==>", res.data);
} catch (error) {
// handle error
}
I had a similar problem. As others have pointed out, axios reads the json as a js object and you can easily move through the hierarchy to get your field data.
However, for me axios did not want to read the json as an object and instead returned a string. The cause was that there was a hanging comma at the end of the json due to a previous row deletion in the file. So the file content wasn't valid json, and axios simply returned a string.
Remove the comma, everything worked.
I would suggest to check the json for any incorrect syntax.
I had the same problem and I found that I was not reading data properly. Finally, I got a solution. try this.
my data was like:
response = [{"myname","Anup","age":23,"Education":"Graduation"}]
I was trying to retrieve data like(this was giving output undefined)
axios('https://apiurl.com')
.then((reponse)=>{
const recieved_Data=fetchdata.data;
console.log(recieved_Data.name);
})
Correct Approach:
axios('https://apiurl.com')
.then((reponse)=>{
const recieved_Data=fetchdata.data;
console.log(recieved_Data[0].name);
})
as you can see i have passed the index value of the array of my response recieved_Data[0].name And this gave me the correct output.
Vote me if this works for you.
Thanks!
So I came across this post in search of an answer to my question. "How to access data in a json file returned by an api." Nonetheless, what worked for me at the end of the day was an answer to a similar question on stackoverflow to which the link is Axios. How to get error response even when api return 404 error, in try catch finally.
However, here is the code I used to access my error codes returned by my backend api.
axios.get(/sanctum/csrf-cookie).then(response => {
axios.post(api/register, registerInfo)
.then(response => {
console.log('This is the response: ' + response.data.errors);
}).catch(error => {
console.log('This is the error: ' +
error.response.data.errors.name);
});
});
I've got a provider that uses the Http service to perform a GET operation over a localhost server:
requestAchievedCombined(config){
return new Promise( (resolve, reject) => {
const URL = "localhost:3000";
const query = "?collection=achieved_combined&query=columns";
this.http.get(URL+"/api"+query).subscribe( response => {
// TODO: check data integriy
console.log(">> API RES: ", response)
resolve(response);
}, err => this.errorHandler(err, reject));
})
}
The server is hosted in localhost:3000 and running, and it works perfectly when called from the navigator with that same GET query string... it returns some JSON.
Thing is, when I execute my Angular app, this gives me the following error:
ERROR [DataRequester] =>
{…}
_body: "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<title>Error</title>\n</head>\n<body>\n<pre>Cannot GET /function%20URL()%20%7B%20%20%20%20[native%20code]%7D/api</pre>\n</body>\n</html>\n"
headers: Object { _headers: Map, _normalizedNames: Map }
ok: false
status: 404
statusText: "Not Found"
type: 2
url: "http://localhost:4200/function%20URL()%20%7B%20%20%20%20[native%20code]%7D/api?collection=achieved_combined&query=columns"
__proto__: Object { constructor: Response(), toString: Response.prototype.toString() }
Do anybody know why this happens? What am I doing wrong? I'm using the latest Angular version.
pd: yes I tried putting http:// before localhost in the URL.
EDIT: After changing the url to http://localhost:3000 and call the property in a proper way (I was forgetting the this. thing), I could manage to communicate with the server, but now I'm having this issue:
ERROR [DataRequester] =>
{…}
_body: error
bubbles: false
cancelBubble: false
cancelable: false
composed: false
currentTarget: null
defaultPrevented: false
eventPhase: 0
explicitOriginalTarget: XMLHttpRequest { __zone_symbol__xhrSync: false, __zone_symbol__xhrURL: "http://localhost:3000/api?collection=achieved_combined&query=columns", readyState: 4, … }
isTrusted: true
lengthComputable: false
loaded: 0
originalTarget: XMLHttpRequest { __zone_symbol__xhrSync: false, __zone_symbol__xhrURL: "http://localhost:3000/api?collection=achieved_combined&query=columns", readyState: 4, … }
target: XMLHttpRequest { __zone_symbol__xhrSync: false, __zone_symbol__xhrURL: "http://localhost:3000/api?collection=achieved_combined&query=columns", readyState: 4, … }
timeStamp: 3687.8557595446277
total: 0
type: "error"
__proto__: ProgressEventPrototype { lengthComputable: Getter, loaded: Getter, total: Getter, … }
headers: Object { _headers: Map, _normalizedNames: Map }
ok: false
status: 0
statusText: ""
type: 3
url: null
__proto__: Object { constructor: Response(), toString: Response.prototype.toString() }
URL is a global function that gets "called". Try renaming the URL var to url and it should work.
Okay, first thing wrong was that I wasn't calling the URL property in a good way: actually, it wasn't in the method but in the class, and I was forgetting the "this.", so I wasn't pointing to the right variable.
Secondly, fixed my edit simply setting up CORS in my express server:
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
Now my Angular app correctly gets the data!
I'm just passing by to give you some code
requestAchievedCombined(config): Observable<any> {
const URL = "localhost:3000";
const query = "?collection=achieved_combined&query=columns";
return this.http.get(URL+"/api"+query)
.map( response => {
// TODO: check data integriy
console.log(">> API RES: ", response)
return response;
}, err => this.errorHandler(err))
// .toPromise() // If you still want your cherished promise
;
}
I've changed your function to simplify it : you should use Observables instead of Promises. I know, I was skeptical at first too, but Observables are way more powerful than promises. and if you still don't like it, simply call .toPromise() right after the map operator, it will still be clearer ;)
Other than that, Could you post the trace of your error instead of the payload ? We need the error message to know what is happening.