使用角度服务将基本身份验证传递给Rest API

时间:2018-12-26 16:37:05

标签: node.js angular express

我想使用角度身份验证登录,但是在将数据从服务发送到Express Rest API时,它将显示401未经授权的错误。

login(data) {
  console.log(data);
  const headers_object = new HttpHeaders().append('Content-Type', 'application/x-www-form-urlencoded');

  headers_object.append('Authorization', 'Basic ' + btoa(data.email + ':' + data.password));

  return this.Httpclient.post('http://api/auth', data, {
    headers: headers_object
  })
  .pipe(map((res: Response) => {
    return res.json();
  }));

}

我在其他API中使用了特快护照

Request URL: http://api/auth
Request Method: POST
Status Code: 401 Unauthorized
Remote Address:api
Referrer Policy: no-referrer-when-downgrade
Access-Control-Allow-Headers: bugsnag-api-key,bugsnag-payload-version,bugsnag-sent-at,content-type
Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE
Access-Control-Allow-Origin: *
Allow: POST, GET, OPTIONS, PUT, DELETE
Connection: keep-alive
Date: Wed, 26 Dec 2018 16:13:13 GMT
Transfer-Encoding: chunked
WWW-Authenticate: Bearer realm="Users"
X-Powered-By: Express
Provisional headers are shown
Accept: application/json, text/plain, */*
Content-Type: application/x-www-form-urlencoded
Origin: http://localhost:4200
Referer: http://localhost:4200/login
User-Agent: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36
{"email":"","password":"","access_token":""}: 

用于发布方法登录验证的Express api处理程序

import { Router } from 'express'
import { login } from './controller'
import { password, master, facebook, github, google } from '../../services/passport'

const router = new Router()

/**
 * @api {post} /auth Authenticate
 * @apiName Authenticate
 * @apiGroup Auth
 * @apiPermission master
 * @apiHeader {String} Authorization Basic authorization with email and password.
 * @apiParam {String} access_token Master access_token.
 * @apiSuccess (Success 201) {String} token User `access_token` to be passed to other requests.
 * @apiSuccess (Success 201) {Object} user Current user's data.
 * @apiError 401 Master access only or invalid credentials.
 */
router.post('/',
  master(),
  password(),
  login)

1 个答案:

答案 0 :(得分:0)

append()不会修改标题。它创建一个 new HttpHeaders对象并返回它。所以你需要

let headers_object = new HttpHeaders().append('Content-Type', 'application/x-www-form-urlencoded');
headers_object = headers_object.append(...);

或者简单地

const headers_object = new HttpHeaders().append(...)
                                        .append(...);