0

I am new to react and new to jspdf pdf creator. I am getting the following error in my jspdf file when I click download.

enter image description here

It shows cors policy error:

This is the function where I am generating the pdf :

generatePDF = () => {
    window.html2canvas = html2canvas;

    var doc = new jsPDF("p", "pt", "a4");

    doc.html(document.querySelector("#content"), {
      callback: function(pdf) {
        pdf.save("Coil_Details.pdf");
      }
    });
  };

This is the function where I am getting the data:

getData = async () => {
    var ID = this.props.id;
    var promise = await this.getAuthorization();
    console.log("ID:" + ID);

    axios({
      method: "GET",
      url: serverDetails.jwtTokenGenerationURL,
      params: {
        "jwt-token": jwtService.GetJWT()
      }
    })
      .then(response => {
        if (response.statusText != "" && response.statusText != "OK") {
          return Promise.reject(response.statusText);
        } else {
          serverDetails.jwtResponse = response.data;

          //return response.data;
        }
      })

      .then(response => {
        var url = "api/observation/GetCoilImages";
        url += "?jwt=" + serverDetails.jwtResponse;
        url += "&ID=" + ID;
        axiosAPI
          .get(url)

          .then(response => {
            if (response.statusText != "" && response.statusText == "OK") {
              // window.open(response.data, '_blank');

              console.log("Response:" + response.data);
              console.log("Response1:" + response.data[0]);
              var code = [];
              for (var i in response.data) {
                code[i] = response.data[i];
                console.log("Code:" + code);
              }
              this.setState({ code });
            }

            this.setState({
              modal: !this.state.modal
            });
          });
      });
  };

The corresponding C# method is like this:

[HttpGet]
        [Route("GetCoilImages")]
        public IHttpActionResult GetCoilImages(string jwt, string ID)
        {

            List<string> coilURL = new List<string>();
            

            string connectionstring = Utilities.SQL_DB1;// our SQL DB connection
            SqlConnection conn1 = new SqlConnection(connectionstring);

            DataTable dt = new DataTable();

            string query = "Select CCD_IMAGE_URL from T_CQL_COIL_DESC where CCD_COIL_ID = '" + 
             ID + "'";

            //SqlConnection conn = new SqlConnection(connectionstring);
            SqlCommand cmd = new SqlCommand(query, conn1);
             conn1.Open();

            


            // create data adapter
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            // this will query your database and return the result to your datatable

            
            da.Fill(dt);

             if (dt.Rows.Count > 0)
            {
            for (int i = 0; i < dt.Rows.Count; i++)
                {
                    coilURL.Add(imgurl+dt.Rows[i]["CCD_IMAGE_URL"].ToString());
                }
            }




            conn1.Close();
            da.Dispose();
            return Ok(coilURL);


        }

I have also handled cors policy in web.api.config, like so:

namespace coilQuality
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            var cors = new EnableCorsAttribute("*", "*", "*");
            config.EnableCors(cors);
            

            var constraints = new { httpMethod = new HttpMethodConstraint(HttpMethod.Options) };
            config.Routes.IgnoreRoute("OPTIONS", "*pathInfo", constraints);

            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}

How do I solve this CORS issue not using extensions in crome like allow cors or cors unblock. Please help??

sambit
  • 256
  • 2
  • 18

1 Answers1

0

The CORS policy (Cross-origin resource sharing) in general means that cross-site requests (from your site (localhost) to another site (firebase API) ) is not allowed, unless the resource server explicitly whitelist you, through the use of an "Access-Control-Allow-Origin" header.

It seems that the Firebase API is blocking your request because the request comes from an unallowed source, so you need to configure your Firebase settings to allow requests from your localhost. I am not familiar with FirebaseStorage, but I came across some other answer that may help (or just Google "firebase storage api cors localhost")

Bao Huynh Lam
  • 974
  • 4
  • 12
  • Is there something I can do at my end without touching firebase? – sambit Jun 27 '21 at 14:56
  • Most probably not. In general principle, it just does not make sense if the user can config settings to allow himself - the resource server must explicitly whitelist the user's source. I am afraid you must tweak Firebase – Bao Huynh Lam Jun 27 '21 at 15:01