Im using my api from the rest framework, when I got to the URL from the api it shows’s it correct. But when I consume it the response seems to be null.
Im hosting both project (front vuejs and back django) in diferents ports (8080 and 8000, respectively). CORS are allowed.
I’ve tried with another tools like fetch or jquery and seems to be the same.
Js:
export class APIService {
contructor() {}
get_user_id(){
const url = `http://localhost:8000/api/v1/user-id/\`;
return axios.get(url).then(function (response) {
console.log(response); // For testing
return response.data;
});
}
}
Django api view, for that url:
class UserIdLoggedView(APIView):
def get(self, request):
user = request.user
return Response({
‘id’: user.id,
})
For this case I didn’t need a serializer.
This is how the django rest shows it:
{ HTTP 200 OK
Allow: GET, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept
{
“id”: 1
}
And this is the output of the response from the console (just the data part)
data:
id: null
Instead of return id=1 as expected it return null.
Solution :
why are you using two return statements in get_user_id? You hit the first return statement and it doesn’t wait for the promise to be fulfilled. Basically, you send the get request but don’t wait for the response. Also, I would recommend creating a base instance of axios as a vue.js plugin.