1

Working with Fetch API to get the data from service after posting formdata, which is not return any proper data. Always returns opaque response. But i need cross-origin to get/post the data. here is my code.

         fetch('http://localhost:3000/default/index', {
            method: 'POST',
            body: formData,
            mode: 'no-cors',
            headers: {
                'Accept': 'application/json, text/plain, */*',
                'Content-Type': 'application/json'
              }
        }).then(function (response) {
            return response.json();
        }).then(function (data) {
            debugger;
        }).catch(function (error) {
            console.log(error);
        });

After running the script got this,

enter image description here

I need the proper response which returned from server side.

NOTE: In Network tab i can see the proper stringified response, still i can't get it in then function response.

Shanmu_92
  • 835
  • 1
  • 7
  • 20
  • `mode: 'no-cors',` why? Do you know what it does? – Phil May 14 '19 at 05:52
  • For cross-origin. – Shanmu_92 May 14 '19 at 05:53
  • If i add cors or anything, it is not hit in server side. Since both urls are different. – Shanmu_92 May 14 '19 at 05:53
  • `no-cors` does not enable cross-origin requests. See [`Request.mode`](https://developer.mozilla.org/en-US/docs/Web/API/Request/mode) – Phil May 14 '19 at 05:56
  • I'm curious why don't you set Access-Control-Allow-Origin to your header in your backend's responses – Thai Doan May 14 '19 at 06:02
  • If i remove no-cors it does't hit to server side. Event i set Access-Control-Allow-Origin in headers. @ThaiDoan – Shanmu_92 May 14 '19 at 06:11
  • FYI, `Access-Control-Allow-Origin` is a **response** header. It must come from your server-side – Phil May 14 '19 at 06:15
  • Set what u suggested still i can this error: `Access to fetch at 'http://localhost:60858/Default/Index' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status` @Phil – Shanmu_92 May 14 '19 at 06:22
  • You also need to support pre-flight `OPTIONS` requests. See https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS. Most server-side tech has some sort of middleware to add CORS support. You should see if you can find one for yours, eg https://expressjs.com/en/resources/middleware/cors.html – Phil May 14 '19 at 06:24
  • @Phil is this possible to get exact error in catch statement? Always returns failed to fetch. (e.g. when i set incorrect Url, i need to see the error like internal server error) – Shanmu_92 May 22 '19 at 05:35

0 Answers0