typescript 如何以角度 4 在帖子正文中发送数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49851892/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to send data in post body in angular 4
提问by MANOJ
Below is the code to make post request:
下面是发出post请求的代码:
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});
}
}
Below is the node code where I am trying to access the request body, Request body is null in the helow case:
下面是我试图访问请求正文的节点代码,在下面的情况下,请求正文为空:
router.use(express.static(path.join('webpage')));
var bodyParser = require('body-parser');
router.use(bodyParser.urlencoded({ extended: true }));
router.post('/api/auth', function(req, res){
console.log(req.body);
console.log(req.body.username + ":" + req.body.password);
});
回答by MANOJ
Request was sent successfully using below method:
使用以下方法成功发送请求:
Angular:
角度:
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;
}
);
}
Node
节点
var bodyParser = require('body-parser');
router.use(bodyParser.json());
router.post('/api/auth', function(req, res){
console.log("request received " + req.body);
});
回答by erosb
You should send a formdata request instead of a JSON payload.
您应该发送一个 formdata 请求而不是一个 JSON 负载。
First, you have to set the proper content type header:
首先,您必须设置正确的内容类型标题:
const headers = new HttpHeaders({
'Content-Type': 'application/x-www-form-urlencoded'
});
Second, you have to send a FormData
object:
其次,您必须发送一个FormData
对象:
const data = new FormData();
data.append("username", username);
data.append("password", password);
// ...
return this.http.post<any>(this.authUrl, data, {headers: headers});