Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

737
Views
Fail to send JSON HTTP POST, but succeed to send text HTTP POST. why?

I want to send a JSON http POST from an HTML page. The Fetch API is used here. It can be successfully posted if the content-type is "application/x-www-form-urlencoded" or "text/plain", but fails to post if the content-type is "application/json". I have tried Both Fetch and Axios API. But JSON can be posted successfully posted from an online http tool (https://reqbin.com/) enter image description here

Here is my client code in HTML:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>test</title>
</head>
<body>
<h1 id ="h1">post test</h1>
<input type="submit" value="post" onclick="sendpost()">
<script>
    function sendpost()
    {
        const Url = 'https://my-worker.sgcloud.workers.dev/';

        const data = {
            name: 'moe',
            age: '50'
        };

        fetch(Url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        })
            .then(response => response.text()
                .then(text => {
                    document.getElementById("h1").innerHTML = text;
                }))
            .catch(err => console.log(err))
    }
</script>
</body>
</html>

The error in development tool is:

POST https://my-worker.sgcloud.workers.dev/ net::ERR_FAILED

The server is in my cloudflare workers: https://my-worker.sgcloud.workers.dev/ , Access-Control-Allow-Origin is on. You can try to post to my server. the server code is:

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request));
});

async function handleRequest(request) {
  if (request.method == 'GET') {
  return new Response('Hello Worker!', {
    headers: { 'content-type': 'text/plain', 'Access-Control-Allow-Origin': '*' },
  });
  } else if (request.method == 'POST') {
  return new Response('Response for POST!', {
    headers: { 'content-type': 'text/plain', 'Access-Control-Allow-Origin': '*' },
  });
  } else {
    response = new Response('Expected POST', { status: 500 });
  }
}

because I can post json from the online tool, so my client code should have some problem to send application/json (the client code can send text/plain or application/x-www-form-urlencoded, tested). How shoud I change my code to send json? Thank you

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

I think I know the reason.

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

For Cross-Origin Resource Sharing (CORS) situation: Additionally, for HTTP request methods that can cause side-effects on server data (in particular, HTTP methods other than GET, or POST with certain MIME types), the specification mandates that browsers "preflight" the request, soliciting supported methods from the server with the HTTP OPTIONS request method, and then, upon "approval" from the server, sending the actual request.

Some requests don't trigger a CORS preflight. Those are called simple requests. The only type/subtype combinations allowed for the media type specified in the Content-Type header are: application/x-www-form-urlencoded multipart/form-data text/plain.

application/json is not suitable for this situation, so I can not post json, but can post text.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!