首页 > 解决方案 > 角度 http.get 发送请求失败错误

问题描述

我发送带有令牌的获取请求 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."
            });
        });
    });
});

我知道发送方式不对

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

从服务器

标签: angulartoken

解决方案


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

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


推荐阅读