从AngularJS升级时,HttpClient POST在Angular 6上失败

时间:2019-02-25 23:53:03

标签: angularjs angular angular-httpclient

我正在将应用程序从Angular 1.6升级到Angular 6,并且停留在登录屏幕中。以下是我要执行的操作的代码段-

const body = new URLSearchParams();
body.set('username', 'admin')
body.set('password', 'admin');

this.http.post('/log-in',
  body,
  {
    headers: new HttpHeaders()
      .set('Content-Type', 'application/x-www-form-urlencoded')
  }
).subscribe((response: Response) => {
  // Do something here 
}

这是我收到的错误,即使服务器的响应是200-

SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse (<anonymous>)
at XMLHttpRequest.onLoad (http.js:1514)
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:423)
at Object.onInvokeTask (core.js:3811)
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:422)
at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (zone.js:195)
at ZoneTask.push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask [as invoke] (zone.js:498)
at invokeTask (zone.js:1744)
at XMLHttpRequest.globalZoneAwareCallback (zone.js:1781)

很明显,预期的响应是JSON,但我收到的是HTML页面

{error: SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse (<anonymous>)   
at XMLHtt…, text: "<!DOCTYPE html>↵<html lang="en" layout ng-app="pfs…rc="scripts/index.js"></script>↵↵</body>↵</html>↵"}

我已经进行了很多搜索,以找出解决方法,但到目前为止没有任何进展。尝试了

中的建议

HttpClient POST request using x-www-form-urlencoded

How to force Angular2 to POST using x-www-form-urlencoded

但它们都不能解决问题。我还尝试更改了httpOptions的 responseType ,仍然遇到相同的错误。

这是有效的AngularJS(1.6)代码-

var postHeaders = {
  'Content-Type': 'application/x-www-form-urlencoded'
};    

$http({
      method: 'POST',
      url: '/log-in',
      data: $httpParamSerializerJQLike(
        {username: username, password: password}),
      headers: postHeaders,
    }).then(function (success) {
      // Do something
    }

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

最可能的原因是,您发布到后端的内容格式不正确,因此会引发错误并返回HTML页面。您不应该像发送URLSearchParams一样发送body对象,而应该发送常规对象:

const body = {
    username: 'admin',
    password: 'admin',
};

答案 1 :(得分:0)

完成此操作后,我就可以完成这项工作-我必须在选项中添加以下responseType

return this.http.post('http://localhost/api/v1/log-in',
  body, { responseType: 'text' as 'json' }
)

以前,当我将responseType添加为“文本”时,我一直收到有关类型不匹配的错误。对我来说,关键是将其设置为'text'为'json'