【发布时间】:2019-02-25 23:53:02
【问题描述】:
我正在将我的应用程序从 Angular 1.6 升级到 Angular 6,但我卡在了登录屏幕中。下面是我正在尝试做的代码 sn-p -
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
}
非常感谢任何帮助。
【问题讨论】:
标签: angularjs angular angular-httpclient