简体   繁体   中英

What should the response from backend be to this AngularJS function?

I'm trying to make the following tutorial work which simulates a login from here : http://jasonwatmore.com/post/2014/05/26/AngularJS-Basic-HTTP-Authentication-Example.aspx

Here is the AngularJS code:

/* Dummy authentication for testing, uses $timeout to simulate api call
         ----------------------------------------------*/
        $timeout(function(){
            var response = { success: username === 'test' && password === 'test' };
            if(!response.success) {
                response.message = 'Username or password is incorrect';
            }
            callback(response);
        }, 1000);


        /* Use this for real authentication
         ----------------------------------------------*/
        //$http.post('/api/authenticate', { username: username, password: password })
        //    .success(function (response) {
        //        callback(response);
        //    });

    };

I now want to change it from dummy to the real authentification.

So far I have in the backend:

@CrossOrigin
@RequestMapping(value =  "/login", method = RequestMethod.POST)
public String login(@RequestBody Login login) {
    if (login.username.equals("test") && login.password.equals("test")) {
        //return what?
    } else {
        //return what?
    }
}

You return a normal Java object. The object should automatically be transferred in json format and you can read json format in javascript.

Example:

// java
String name;
int age;

// json format
{"name": "theName", "age": 32}t

// javascript
var myObj = {
    name: "theName",
    age: 32
};

So in your java you return you simply return your java object. If you look in your dev console of your browser in the network tab you should see the response in json format. Otherwise just $log.log("response", response); to check what object you get from the server.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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