0

I am trying to post XML string instead of JSON object to node.js server using fetch API.

This is my code which post JSON object:

handleSubmit = async e => {

    e.preventDefault();
    var request = JSON.stringify({
        drug: this.state.drug,
        disease: this.state.disease,
        type: this.state.type    
    });
    var xmlRequest = js2xmlparser.parse("request", request);

    const response = await fetch('/api/submit', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: request
    });

    const body = await response.text();

    this.setState({
        responseToPost: body
    });
}

How to edit the code to post XML string(xmlRequest) instead of JSON (request) in the request body.

1 Answer 1

2

Send xmlRequest instead of request in the body. Also change the Content-Type to text/xml or application/xml

const request = {
    drug: this.state.drug,
    disease: this.state.disease,
    type: this.state.type    
};

const xmlRequest = js2xmlparser.parse('request', request);

const response = await fetch('/api/submit', {
    method: 'POST',
    headers: {
        'Content-Type': 'text/xml'
    },
    body: xmlRequest
});

js2xmlparser takes an object as second argument, don't use JSON.stringify.

Sign up to request clarification or add additional context in comments.

3 Comments

I change the code as above exactly . But , after running the server and print the req body in console console.log(req.body) it print { } empty request !!
You asked how to send xml to the server, and that's how you do it. Check the network tab and see that you're actually sending the XML. Why your server is not accepting it or not, is out of the scope of this question and not something we can tell you with the given information. You should post the server code, or better yet create a different question for that, and I'll be happy to help you.
Why are you sending it in XML if your server can't handle it though? if req.body is empty, it means you are not parsing XML. You should implement or use an XML body parser...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.