如何在Angular 4中发送POST请求的数据体?

7
以下是进行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});
    }
}

以下是我试图访问请求主体的节点代码,但在下面的情况下,请求主体为空:
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);
});

你为什么要在客户端手动将body转换为字符串,以及在服务器上使用URL编码解析器? - jonrsharpe
1
这是你应该查看的内容:https://angular.io/guide/http - Dheeraj Kumar
2个回答

8

以下方法成功发送了请求:

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);
});

从Express v4.0开始,使用app.use(express.json());代替bodyParser的两行代码 - var bodyParser = require('body-parser'); router.use(bodyParser.json()); - Vibhor Dube

0
如果请求体负载包含 application/x-www-form-urlencoded 值,则 post 方法期望像下面这样的字符串值:const body = 'client_id=ApiClient&grant_type=password&scope=UiApi&username=' + username +'&password=' +password;。该字符串应该作为请求体传递给 API。
getLoginCredentialsAccessToken(username: string, password: string) 
: Observable<AccessToken>{

const headersList = new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded' });

const body = 'client_id=ApiClient&grant_type=password&scope=UiApi&username=' + username +'&password=' +password;
     
return this.http.post<AccessToken>(this.tokenEndpoint, body, { headers: headersList});
  }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接