如何以角度4在帖子正文中发送数据

MAN*_*NOJ 7 http node.js typescript angular

下面是发出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});
    }
}
Run Code Online (Sandbox Code Playgroud)

下面是我试图访问请求正文的节点代码,在下面的情况下,请求正文为空:

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);
});
Run Code Online (Sandbox Code Playgroud)

MAN*_*NOJ 7

使用以下方法成功发送请求:

角度:

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

    }
Run Code Online (Sandbox Code Playgroud)

节点

var bodyParser = require('body-parser');
router.use(bodyParser.json());

router.post('/api/auth', function(req, res){
  console.log("request received " + req.body);
});
Run Code Online (Sandbox Code Playgroud)