将数据从客户端angular2发送到服务器spring' POST'

时间:2016-05-06 13:50:18

标签: spring rest http angular

我没有任何错误,但我在服务器端获取数据null 你可以举一个例子来帮忙吗

这是我的客户服务

import {Injectable, Inject} from "angular2/core";
import {Http, Headers} from "angular2/http";
import 'rxjs/add/operator/map';
import {User} from "../User/User";


@Injectable()
export class loginService {

    constructor(private _http:Http) {

    }

    login(user) {

        // var creds = "username=" + "khalil" + "&password=" + 3;   .map(res=>res.text());
        var headers = new Headers();
        headers.append('Content-Type', 'application/json');
        return this._http.post('http://localhost:8080/login', user, {
                headers: headers
            })
            .map(res=>res.json());

    }

这是我调用登录方法的组件

import {Component, Inject} from 'angular2/core';
import {Router} from "angular2/router";
import {loginService} from "./login.service";
import {HTTP_PROVIDERS, Http} from "angular2/http";
import {User} from "../User/User";
import {ControlGroup, FormBuilder, Validators, Control} from "angular2/common";

@Component({
    selector: 'login',
    templateUrl: '../dev/login/login.html',
    providers: [HTTP_PROVIDERS, loginService]
})

export class loginComponent {
    public _user:User;
    loginForm:ControlGroup;

    constructor(private _router:Router,
                private _loginService:loginService,
    private _formBuilder:FormBuilder) {


        this._user = {
            firstName: '',
            lastName: '',
            tel: '',
            email: '',
            creationDate: new Date(),
            compteMatriculaire: '',
            enabled: false,
            password: '',
            structure: ''
        };

    }

    login() {
        console.log("email"+this._user.email);
        this._loginService.login(this._user).subscribe(
            (data:User) => {
               this._user = data;
            },
            error => alert('Erreur ' + error),
            () => {
                console.log("finished  " + this._user.email + "   " + this._user.password);
                //this._router.navigate(['Home']);
            }
        );
    }

这是我的表单页面

<div class="container">

    <form #loginForm="ngForm" (ngSubmit)="login()" class="form-signin">
        <h2 class="form-signin-heading">Please sign in</h2>
        <label for="email" class="sr-only">Email</label>
        <input type="email"  ngControl="email" [(ngModel)]="_user.email" #email id="email"  class="form-control" placeholder="email" required autofocus>
        <label for="password" class="sr-only">Password</label>
        <input type="password" ngControl="password" [(ngModel)]="_user.password" #password id="password"  class="form-control" placeholder="Password" required>
        <div class="checkbox">
            <label>
                <input type="checkbox" value="remember-me"> Remember me
            </label>
        </div>
        <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
    </form>
</div>

这是我的控制器

@RequestMapping(value = "/login", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<User_khalil> login(User_khalil user) {
        System.out.println("------- " + user.getEmail() + user.getPassword());

        User_khalil u = userRepository_khalil.findOneByEmailAndPassword(user.getEmail(), user.getPassword());
        if (u != null) {
            return new ResponseEntity<User_khalil>(user, HttpStatus.OK);
        }
        return new ResponseEntity<User_khalil>(user, HttpStatus.OK);
    }

3 个答案:

答案 0 :(得分:2)

public ResponseEntity<User_khalil> login(@RequestBody User_khalil user)

@RequestBody是此解决方案的关键。

另一个选项(没有@RequestBody):

  this._http.post('http://localhost:8080/login', user, {
  headers: headers,
  params: new HttpParams().set('username', 'Khalil'),
})

通过这种方式,您将POST请求发送到URL / api / login?username = Khalil。

我建议使用@RequestBody的第一个选项。

答案 1 :(得分:0)

您忘记使用JSON.stringify函数将对象转换为字符串:

return this._http.post('http://localhost:8080/login', 
        JSON.stringify(user), { // <------
            headers: headers
        })
        .map(res=>res.json());

修改

您可以尝试以下方法:

return this._http.post('http://localhost:8080/login', 
        JSON.stringify({
          email: user.email,
          password: user.password
        }), {
            headers: headers
        })
        .map(res=>res.json());

答案 2 :(得分:0)

login() { console.log("email"+this._user.email); this._loginService.login(this._user).subscribe( data => { console.log(data); this._user = data; }, error => alert('Erreur ' + error), () => { console.log("finished " + this._user.email + " " + this._user.password); //this._router.navigate(['Home']); } ); }