【问题标题】:Angular 5 http service response errorAngular 5 http服务响应错误
【发布时间】:2019-01-30 08:34:46
【问题描述】:

我正在尝试使用带有 xml 响应的 http RSS 服务。

我得到响应状态 OK(200) 并出现以下错误:

在 XMLHttpRequest.onLoad 的 JSON.parse() 的位置 0 处的 JSON 中的意外标记

我做错了什么,如何解析 xml 响应?

Component.ts 代码:

this.ns.nBasicApi().subscribe((jsonFromServer) => { 
  this.response = jsonFromServer;
});

服务代码:

nBasicApi():any {
  return this.http.get('http://localhost:3000/api/stocks');
}

服务器代码 App.js:

const fetch = require('isomorphic-fetch');
const express = require('express');
const app = express();
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 
'GET,POST,OPTIONS,DELETE,PUT');
res.header('Access-Control-Allow-Headers','Accept,Accept- 
Language,Content-Language,Content-Type');
res.header('Access-Control-Expose-Headers','Content- 
Length,Content-Range');
next();
})
app.route('/api/stocks').get((req, res) => {
 fetch('http://www.nasdaq.com/aspxcontent/NasdaqRSS.aspx? 
data=quotes&symbol=NFLX').then((res) => { 
         return res.text();
 }).then((json) => {
     res.send(json)
 })
});

【问题讨论】:

    标签: xml angular http service rss


    【解决方案1】:

    据我所知,Angular 中没有解析 XML 的内置方法,因此您需要找到一些库和 map 响应。默认情况下,Angular 将响应视为 JSON,因此存在解析错误。要禁用自动解析,请使用 {responseType: 'text'}

    nBasicApi():any {
      return this.http.get('http://localhost:3000/api/stocks', {responseType: 'text'});
    }
    

    【讨论】:

    • 正确。默认情况下,Angular 不识别 XML,但是通过使用 {responseType: 'text'} 的技巧,您只是告诉 observable 您正在传递一些字符串,然后他将不得不手动将 xml 转换为 json
    【解决方案2】:

    Angular 不支持 XML。 Angular 默认支持 json。尝试使用像下面这样的 npm 包

    npm install xml2js -g 导入服务文件为:import * as xml2js from 'xml2js';

    例子

    let formdata = new URLSearchParams();
    formdata.set('username','username');
    formdata.set('pw','pw'); 
    let headers = new Headers({'Content-Type': 'application/x-www-form-urlencoded' });
    
    let options = new RequestOptions({ headers: headers, method: RequestMethod.Post});
    
    postData () {
    
         this.http.post(this._yourUrl, formdata.toString(), options)
         //convert to JSON here
         .map(res => {
                xml2js.parseString( res.text(), function (err, result) {
                console.dir(result); // Prints JSON object!
             });
         })
         .subscribe(data => { 
              console.log(data);              
         });
    }
    

    或者看看这个 jsfiddle http://jsfiddle.net/abdmob/gkxucxrj/1/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-29
      • 1970-01-01
      • 1970-01-01
      • 2018-09-03
      • 2018-06-04
      • 1970-01-01
      • 2018-02-17
      相关资源
      最近更新 更多