以下是发布请求的代码:
foo@.Data
以下是我尝试访问请求正文的节点代码,请求正文在以下情况下为空:
export class AuthenticationService {
private authUrl = 'http://localhost:5555/api/auth';
constructor(private http: HttpClient) {}
login(username: string, password: string) {
console.log(username);
let data = {'username': username, 'password': password};
const headers = new HttpHeaders ({'Content-Type': 'application/json'});
//let options = new RequestOptions({headers: headers});
return this.http.post<any>(this.authUrl, JSON.stringify({data: data}), {headers: headers});
}
}
答案 0 :(得分:0)
您应该发送formdata请求而不是JSON有效负载。
首先,您必须设置正确的内容类型标题:
const headers = new HttpHeaders({
'Content-Type': 'application/x-www-form-urlencoded'
});
其次,你必须发送一个FormData
对象:
const data = new FormData();
data.append("username", username);
data.append("password", password);
// ...
return this.http.post<any>(this.authUrl, data, {headers: headers});
答案 1 :(得分:0)
使用以下方法成功发送了请求:
<强>角:强>
login(username: string, password: string) {
const data = {'username': username, 'password': password};
const config = { headers: new HttpHeaders().set('Content-Type', 'application/json') };
return this.http.post<any>(this.authUrl, data, config)
.map(res => {
console.log(res);
if (res.user === true) {
localStorage.setItem('currentUser', res.user);
localStorage.setItem('role', res.role);
}
return res;
},
err => {
return err;
}
);
}
<强>节点强>
var bodyParser = require('body-parser');
router.use(bodyParser.json());
router.post('/api/auth', function(req, res){
console.log("request received " + req.body);
});