【问题标题】:angular http.get send requst failed error角度 http.get 发送请求失败错误
【发布时间】:2019-01-28 09:47:20
【问题描述】:

我发送带有令牌的获取请求 url,但它抛出错误

Response {_body: "{"auth":false,"message":"No token provided."}", status: 403, ok: false, statusText: "Forbidden", headers: Headers, …}
headers: Headers {_headers: Map(1), _normalizedNames: Map(1)}
ok: false
status: 403
statusText: "Forbidden"
type: 2
url: "http://localhost:3000/api/url"
_body: "{"auth":false,"message":"No token provided."}"

我的服务

getBusinesses(){
    const token = localStorage.getItem('token');
    return this
    .http
    .get(`${this.uri}`, token).subscribe(res => console.log('Done'));
  }

我的后台服务

router.get('/', VerifyToken, function (req, res) {
    var token = req.headers['x-access-token'];
    decoded = jwt.verify(token, config.secret);
    User.findById(decoded.id, { password: 0 }, function (err, user) {
        if (err) return res.status(500).send("There was a problem finding the user.");
        if (!user) return res.status(404).send("No user found.");
        Report.find({
            username: user.username,
        })
            .then(report => {
            // res.send(report);
        result = report.reduce(function (r, a) {
            r[a.username] = r[a.username] || [];
            r[a.username].push(a);
            return r;
        }, Object.create(null));
        res.send(result);
        // console.log(result);
        }).catch(err => {
            res.status(500).send({
                message: err.message || "Some error occurred while retrieving Report."
            });
        });
    });
});

我知道发送方式不对

你能请任何人解释如何发送请求并获得响应

来自服务器

【问题讨论】:

  • 这种方式不能注入token,看看here
  • 我用这个方法:let headers = new Headers({ 'Authorization': 'Bearer ' + this.authenticationService.token }); let options = new RequestOptions({ headers: headers }); returh this.http.get(url, options)

标签: angular token


【解决方案1】:

你是通过正文发送令牌,你必须通过标题发送它

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type':  'application/json',
    'Authorization': 'my-auth-token'
  })
};

addHero (hero: Hero): Observable<Hero> {
  return this.http.post<Hero>(this.heroesUrl, hero, httpOptions)
    .pipe(
      catchError(this.handleError('addHero', hero))
    );
}

https://angular.io/guide/http#adding-headers

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-24
    • 2019-07-17
    • 2017-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-25
    相关资源
    最近更新 更多