javascriptreactjsflaskfetch-apiflask-restful

Fetch and postman response are different


I am writing my react flask-rest site and and encountered unusual behavior ... of something. So when I create a get request at the address domain/api/users/1, where 1 = id of deleted database element in postman my response consist of one null element (as written in the code), but when I create this request in fetch I get error 410. I have a check for the existence of an element in the code, but this response does not allow my code to execute and all the logic of the program breaks. Moreover, when using a fetch, information about such a request does not even appear in the flask log (when using Postman, everything is fine). So maybe I write a lot of unnecessary information, but I really don't understand what is wrong.

Python code:

def get(self, id):
    u = User.query.filter_by(id=id).first()
    if u:
        return {
            'id': u.id,
            'username': u.username,
            'email': u.email}

If id is not exist return null (works with IDs that never existed).

js-react code:

const [user, setUser] = useState({});

useEffect(() => {
    fetch(`/api/users/${match.params.id}`)
        .then((res) => res.json())
        .then((data) => setUser(data))

    // eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

if (!user) {
    return <h1>Same user dont exists</h1>;
}

return (
    <>
        <h1 className="mb-3">{user.username}</h1>
        <div>{user.email}</div>
    </>
);

Solution

  • Not sure if this solves your problem, but you can try adding an else: block in case the user id does not exist and return an empty dictionary

    def get(self, id):
        u = User.query.filter_by(id=id).first()
        if u:
            return {
                'id': u.id,
                'username': u.username,
                'email': u.email}
        else:
            return {}
            # alternatively:
            # return {"message": "User does not exist"}, 404
    

    I dont know why this works for you one way but not the other, but it seems like not returning anything at all might break your code. Alternatively, return a 404 not found if the user doesnt exist, and handle the case separately based on the status code.

    Also; I dont know why or how your server returns a 410 GONE. If I test a route with no explicit return, I get a 200 OK and the response body is "null". There might be more code involved than you posted in your question.