0

This is the function i am using to get the preferred movie list from the mongodb.

function PreferedMovieData() {
    var init_var = {method: 'POST',
                    mode: 'no-cors',
                    headers: {
                        'Content-Type': 'application/json',
                        'Accept': 'application/json',
                        'Access-Control-Allow-Origin':  'http://127.0.0.1:5001',
                        'Access-Control-Allow-Methods': 'POST',
                        'Access-Control-Allow-Headers': 'Content-Type'
                    },
                    body: JSON.stringify({"page_no": 1})
                };
    fetch("http://127.0.0.1:5001/prefered/movies_list", init_var).then(response => {
        return response.text();
    }).then(data => {
        console.log(data)
    });
}
PreferedMovieData();

i am getting the response back as undefined

  • 1
    does it log undefined if you `return response.json()` as well? Also you may be wanting to do a GET instead of a POST – Edon Oct 11 '20 at 07:06
  • 1
    Can you explain why you are using the `no-cors` mode? 99% of the time that mode is completely useless because all it does is not send the `Origin` header – slebetman Oct 11 '20 at 07:49
  • @Edon nope. when i tried with json() i am getting an error Uncaught (in promise) SyntaxError: Unexpected end of input – Arunachalam Oct 11 '20 at 07:55
  • @slebetman when i remove mode i am facing following error. Access to fetch at 'http://127.0.0.1:5001/prefered/movies_list' from origin 'chrome://new-tab-page' 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. – Arunachalam Oct 11 '20 at 07:56
  • is this plain javascript application or you are using node.js? – sandeep joshi Oct 11 '20 at 09:12
  • bcoz as far as i know *fetch API is not available out of the box for NodeJS applications* use the node-fetch package or other similar API. – sandeep joshi Oct 11 '20 at 09:14
  • @Arunachalam Even **with** mode your broser will still be blocking by CORS policy. Only perhaps it will not display an error. Your real problem is that your request is being blocked by CORS. Fix it at the server. You **CANNOT** fix it on the browser as this is designed intentionally like this – slebetman Oct 12 '20 at 04:37

1 Answers1

1

Change your fetch api in this way:

fetch("http://127.0.0.1:5001/prefered/movies_list", init_var).then(response => {
    return response.json();
}).then(data => {
    console.log(data)
});
Shahnawaz Hossan
  • 2,695
  • 2
  • 13
  • 24