Search code examples
javascriptjqueryhttphttp-headershttp-post

Getting error to make an API Post Call using simple HTML


Without adding mode as 'no-cors':

Error : APICALL.html:1 Access to fetch at 'http://url' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I have added mode as 'no-cors' but then i get another error of Bad Request.

Error : APICALL.html:66 POST http://url net::ERR_ABORTED 400 (Bad Request)

Code :

  var data = {
    Name: "Test",
    Category: "Test-Category",
    Mobile: "999999999999",
    Email: "test@gmail.com",
    Question: "Test Question",
  };

  var options = {
    method: "POST",
    mode: "no-cors",
    origin: "*",
    cache: "no-store",
    headers: {
      "Cache-Control": "no-store",
      "Content-Type": "application/json",
    },
    body: data,
  };

  fetch("http://url", options)
    .then((data) => {
      if (!data.ok) {
        throw Error(data.status);
      }
      return data.json();
    })
    .then((update) => {
      console.log(update);
    })
    .catch((e) => {
      console.log(e);
    });

Solution

  • Chinese: 因为存在跨域情况,需要后端服务器开启跨域,允许你访问。 English: The server is not enabled to allow this port to cross domains because of cross domain conditions