Angular 代码注意两点
1. 请求头Content-type': 'application/x-www-form-urlencoded'
2. 传送的数据采用nameOrEmail=bar&password=moe
这种格式
import {User} from './user';
import {Injectable} from '@angular/core';
import {Http, Headers, Response} from '@angular/http';
import {urlString} from '../url.constont';
import {Subscription} from 'rxjs/Subscription';
import {ActivatedRoute, Router} from '@angular/router';
@Injectable()
export class UserService {
constructor(private http: Http, private router: Router) {
}
//application/x-www-form-urlencoded
doLogin(user: User): string {
const body = {nameOrEmail: user.username, password: user.password};
this.http.post(urlString + 'login',
'nameOrEmail=bar&password=moe',
{headers: new Headers({'Content-type': 'application/x-www-form-urlencoded'})}).subscribe(data => {
console.log(data);
});
return null;
}
}
@ResponseBody
@RequestMapping(value = "login",method = RequestMethod.POST)
public Map<String,String> login(@RequestParam(value = "nameOrEmail",required = false) String name, @RequestParam(value = "password",required = false)String password){
if ("li".equals(name) && "123".equals(password)){
Map<String, String> map = new HashMap<>();
map.put("result", "success");
return map;
}
return null;
}
代码注意: Angular 默认Content-Type
就是application/json
因此不必要加入请求头Content-Type:application/json
import {User} from './user';
import {Injectable} from '@angular/core';
import {Http, Headers, RequestOptions, Response, Jsonp} from '@angular/http';
import {urlString} from '../url.constont';
import {Subscription} from 'rxjs/Subscription';
import {ActivatedRoute, Router} from '@angular/router';
@Injectable()
export class UserService {
constructor(private http: Http, private router: Router) {
}
doLogin(user: User): string {
const body = {nameOrEmail: user.username, password: user.password};
this.http.post(urlString + 'login', body ).subscribe(data => {
console.log(data);
});
return null;
}
}
@ResponseBody
@RequestMapping(value = "login",method = RequestMethod.POST)
public Map<String,String> login(@RequestBody User user){
if (user!=null){
Map<String, String> map = new HashMap<>();
map.put("result", "success");
return map;
}
return null;
}