0

For the following created code in react, after I search similar question, I get always an error (seems that the error is return of a promise).

I am using webpack version 3.1.9

In web-pack configuration I did (don't know whether it is necessary):

module.exports = {
...
devServer: {
headers: {
  'Access-Control-Allow-Origin': '*',
  "Access-Control-Allow-Headers": "*"
}
},
...

Here is my code:

var options = {
  method: 'get',
  mode: 'no-cors',
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json',
    'Access-Control-Allow-Headers': '*',
    'Access-Control-Allow-Origin': '*'
  }
};
let _url = 'my url ... web api returns json';
fetch(_url, options)
  .then(response =>
    response
      .json()
      .then(data => ({
        data: data,
        status: response.status
      }))
      .catch(err =>
        /******ERROR: always catch the error *****/
        ({ error_data: err })
      )
  )
  .then(res => {
    console.log(res);
    // console.log(res.status, res.data.title)
  })
  .catch(err => {
    console.log(err);
  });

The error in the line with the asterisks, as code above

SyntaxError: Unexpected end of input at eval

The code was checked for restful api in C#:

I did in the controller code:

public ActionResult Index()
{
    ActionResult x = Json(db.Trainees.ToList(), 
    JsonRequestBehavior.AllowGet);
    //return Content(db.Trainees.ToList().ToString(), 
    "application/json");

    return Json(db.Trainees.ToList(), JsonRequestBehavior.AllowGet);
    // return View(db.Trainees.ToList());
}

I assume it is related to fact that json returns a Promise, as described in: json returns promise

I see that json is problematic. When I change response.json() to response.text() there is no error, but I realize that even I send the options with 'no-cors', I see an information message:

Cross-Origin Read Blocking (CORB) blocked cross-origin response ... with MIME type application/json

Seems that the fetch ignore the options with 'no-cors'.

Any clues, why the code encounters an error?!

Thanks.


Problem had been fixed. In react I did the changes:

var options = {
method: 'GET',
}

... 

In C# restfull api controller I did the changes:

Response.AddHeader("Access-Control-Allow-Origin", "*");               
return Json(db.Trainees.ToList(), "application/json", 
   JsonRequestBehavior.AllowGet);
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
user3834980
  • 41
  • 10
  • `'Content-Type': 'application/json',` — You're making a GET request. There's no content in the request to describe the type of. This is nonsense. – Quentin Oct 15 '18 at 12:50
  • `"Access-Control-Allow-Headers": "*",` and `"Access-Control-Allow-Origin": "*"` are **response** headers (from CORS). They do not belong on the request. – Quentin Oct 15 '18 at 12:51
  • `mode: 'no-cors',` — Do you want to use CORS or not? You're trying to add CORS headers explicitly (and wrongly as mentioned above) so why are you setting the mode to no-cors? – Quentin Oct 15 '18 at 12:51
  • I can't reproduce the problem. When I have a URL that returns JSON, everything is fine. When I have a URL that returns something that is no valid JSON I get the error `SyntaxError: Unexpected end of JSON input` with no mention of `eval` at all. – Quentin Oct 15 '18 at 12:53
  • Check the url: https://registry.npmjs.org/express/latest I got a problem in this url. maybe the problem is web-pack? I put in configuration of web-pack: module.exports = { devServer: { headers: { 'Access-Control-Allow-Origin': '*', "Access-Control-Allow-Headers": "*" } }, Also using chrome version 69.0.3497.100 – user3834980 Oct 15 '18 at 13:10
  • the /express/latest was not a good answer. I created in rest full api code, that returns a json. I will put in the next few moments the code in C# for rest-full api. When I change the code to text() instead of json() it didn't failed, but also didn't return the corrct data. – user3834980 Oct 15 '18 at 13:29
  • I would like to know which url you had checked. – user3834980 Oct 15 '18 at 13:36
  • I see that json is problematic. When I change response.json() to response.text() there is no error, but I realize that even I send the options with 'no-cors', I see an information message: > Cross-Origin Read Blocking (CORB) blocked cross-origin response ... with MIME type application/json Seems that the fetch ignore the options with 'no-cors'. – user3834980 Oct 15 '18 at 14:10
  • If you tell fetch not to use CORS then it will ignore anything you say that requires CORS permission. Setting `no-cors` mode is almost always the wrong choice. – Quentin Oct 15 '18 at 14:16
  • Well, I see that on site: https://stackoverflow.com/questions/43262121/trying-to-use-fetch-and-pass-in-mode-no-cors there is explanation. This is why your site may works. I need to add on the server side the header for Access-Control-Allow-Origin. The response type is opaque and not the correct one. I didn't realize yet how to add header for the request. – user3834980 Oct 15 '18 at 14:22
  • "I didn't realize yet how to add header for the request." — as my first three comments here imply: You do not add any headers yourself. You simply don't set it to no-cors mode. The headers have to be added to the response. – Quentin Oct 15 '18 at 14:24
  • you should close the .then(response => response.json()) – adc Oct 15 '18 at 14:43
  • Well, I finally succeed to use rest-api. You were right about no-cors. No need to put it in option, but I do need to set header value in the site. BTW - what I said about response.json().then it's because json() returns Promise (so I don't need to close the .then(response => response.json()). It didn't work on runtime), and for this thing, my code was better. You can close this issue. Thank you. – user3834980 Oct 15 '18 at 14:51

0 Answers0