Encountering an HTTP parsing failure while sending XML through Angular 5's HttpClient

Struggling to access a local webservice through XML:

Take a look at the code below:

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type':  'text/xml',
    'Accept':  'text/xml',
    'Response-Type': 'text'
  })
};


login() {
    const postedData = `
        <authenticationDetail>
            <userName>myusername</userName>
            <password>mypassword</password>
        </authenticationDetail>`;
    return this.http.post('http://localhost/login.ws', postedData, httpOptions)
    .subscribe(
        result => {
            console.log('This result is' + result);
        },
        error => {
            console.log('There was an error: ', error);
        }
    );
}

The specific error message received reads:

Http failure during parsing for 'http://localhost/login.ws'

Trying to identify and resolve the issue - Any suggestions?

Answer №1

Have you experimented with this code snippet?

const httpOptions = {
    headers: new HttpHeaders({
        'Content-Type':  'text/xml',
        'Accept':  'text/xml',
        'Response-Type': 'text'
    }), 
    responseType: 'text'
};

It is important to note that the responseType must be specified as text not only in the headers but also in the object httpOptions. Failure to do so may result in Angular incorrectly parsing the response as JSON.

Answer №2

Make a modification to your request like so:

login(){ 
const customHeaders = new HttpHeaders(); 
customHeaders = headers.append('Content-Type': 'text/xml'); 
customHeaders = headers.append('Accept', 'text/xml'); 
let body = '<authenticationDetail>' 
           '<username>Username</username>' 
           '<password>Password</password>' 
           '</authenticationDetail>'; 

return this.http.post('localhost/login.ws',body , { headers: customHeaders, responseType: 'text' })
.subscribe(
        res => {
        parseString(res.text(), (err, result) => {
            if (err) {
                return console.log('invalid XML');
            }

            console.log(result);
        })
    },error => {
            console.log('An error occurred: ', error);
        }
    );
}

Answer №3

Experiment

let postedData = '<authenticationDetail>' + 
                 '<userName>myusername</userName>' + 
                 '<password>mypassword</password>' + 
                 '</authenticationDetail>';

Instead of using template string with whitespace char "new line", try the traditional method with regular strings.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Locating the JSON path within an object

Need help with checking if a specific path is present in a JSON object? var data = { "schemaOne": { "name": "abc", "Path": "i.abc", "count": 5347, "subFolders": [ ] }, "schemaTwo": { "name": "cde", "Path": "i.cde", " ...

brings fulfillment except for categories

The new satisfies operator in TypeScript 4.9 is incredibly useful for creating narrowly typed values that still align with broader definitions. type WideType = Record<string, number>; const narrowValues = { hello: number, world: number, } sa ...

Unable to eliminate top margin in Bootstrap 3 affix feature

Struggling to locate the source of the margin-top when utilizing the affix plugin on my Navbar. You can view [my website here] for better understanding. Should I be implementing Javascript to solve this issue? My current skills in that area are not very ...

Display all event date markers, even if some dates are missing

Using the FullCalendar plugin has been a great experience for me. I have managed to successfully read data from a JSON object with the following code: function press1() { var employees = { events: [] }; ...

Insert a scrollbar into the new popup window on Internet Explorer after the window has been opened

I am looking to enable scrolling in a pop-up window after it has been opened. While FireFox offers the 'window.scrollbars' property for this, Internet Explorer does not have a similar feature. Is there a way to add scrolling functionality in IE u ...

I want to modify a class in Angular 8 by selecting an element using its ID and adjust the styling of a div

Is it possible to dynamically add and remove classes using getElementById in Angular 8? I need to switch from 'col-md-12' to 'col-md-6' when a user clicks on the details icon. I also want to modify the style of another div by setting d ...

Trouble accessing nested components in Angular CLI beyond the first level of components

I'm diving into Angular CLI for the first time and trying to recreate a previous web project of mine. I've managed to nest and display components inside the root component successfully, but after that, I'm facing issues referencing any compo ...

How can I search multiple columns in Supabase using JavaScript for full text search functionality?

I've experimented with various symbols in an attempt to separate columns, such as ||, |, &&, and & with different spacing variations. For example .textSearch("username, title, description", "..."); .textSearch("username|title|description", "..."); U ...

What strategy does Node recommend for organizing code into multiple files?

In the midst of my current project, which involves NodeJS and Typescript, I am developing an HTML5 client that communicates with a NodeJS server via web-sockets. With a background in C#, I prefer to organize my code into separate files for different functi ...

To initiate the development environment, execute the following command: `cross-env NODE_ENV=

[email protected] start /Users/ssurisettii/Documents/il-17g5-app cross-env NODE_ENV=development npm run webpack-development sh: cross-env: command not found npm ERR! code ELIFECYCLE npm ERR! syscall spawn npm ERR! file sh npm ERR! errno ENOENT npm ER ...

Problem with exporting default class in Babel/Jest conflict

Currently, I am facing a challenge while testing the code using jest. The issue seems to be related to babel, especially regarding the export of a default class. Here is an example of the code causing the problem... export default class Test { get() { ...

What is the best way to monitor and record the height of a div element in a React application?

Exploring the Height of a Div I am interested in monitoring the height of a div element so that I can dynamically adjust distances based on varying screen widths. The animation should respond to changes in screen width, such as when text stacks and the he ...

The type 'myInterface' cannot be assigned to the type 'NgIterable<any> | null | undefined' in Angular

I am facing an issue that is causing confusion for me. I have a JSON data and I created an interface for it, but when I try to iterate through it, I encounter an error in my HTML. The structure of the JSON file seems quite complex to me. Thank you for yo ...

Controlling numerous websockets using React

I am currently developing a single-page application using React.js with a JSON RPC 2.0 backend API that relies on websockets. Managing multiple websocket connections simultaneously across different React.js components has been a challenge. Initially, I th ...

Tips for adjusting the height of a Safari extension during runtime

After successfully developing a Safari extension, I am facing an issue with adjusting the width and height of the popover dynamically at runtime. Can anyone provide insights on how to modify the dimensions of the popover based on its content? ...

Transforming XML data into HTML format

This XML Data needs to be converted <xml> <0> <id>e1</id> <Product name>vivo Y11s 4G Smartphone, 32GB, 6.51 HD Display Phantom Black</Product name> <Price>197</Price> <Wireless carrier> ...

Combine rows with the same value in the first column of an HTML table

My HTML table has dynamic content, and I need to merge rows in the first column only if their values are identical. You can see an image of the table here. Specifically, if the values in the first column match, those rows should be merged together while le ...

innerhtml does not display the entire array contents

I'm facing an issue with my innerHTML output where it seems to be displaying one less value than expected from the array. I've been unable to pinpoint the exact problem. await fetch(urlbody, bodyrequestOptions) .then((response) => response ...

I am unable to utilize the outcome of a custom hook within a function or within an effect hook

I've developed a unique custom hook that retrieves a list of individuals File: persons.hooks.ts import {useEffect, useState} from "react"; import Person from "../../models/person/Person"; const usePersons = () => { const ...

Enhancing IntelliJ IDEA's autocomplete functionality with JavaScript libraries

Is there a way to add my custom JavaScript library to IntelliJ IDEA 10.5 or 11 for autocomplete functionality? I want to specify that IDEA should recognize and suggest auto-completions for objects from my library. While it sometimes works automatically, ...