Search code examples
node.jscorsglitch-framework

Cross-origin request to glitch.me server


I have created a server on glitch.me and I am trying to serve data from the server but the following error came up. localhost/:1 Access to fetch at 'https://clem-quote-server.glitch.me/quotes' from origin 'http://localhost:3000' has been blocked by CORS policy:

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.

Not really sure how to resolve this

import React, {Component} from "react"

class quotes extends Component {
    constructor(props) {
        super(props);
        this.state = {
            error: null,
            isLoaded: false,
            quotes: quotes
        };
    }

componentDidMount() {
    fetch("https://clem-quote-server.glitch.me/quotes")
      .then(res => res.json())
      .then(
        (result) => {
            this.setState({
            isLoaded: true,
              quotes: result.quotes
          });
        },
        error => {
          this.setState({
            isLoaded: true,
            error
          });
        }
      );
}

    render() {
        const { error, isLoaded, quotes } = this.state;
        if (error) {
            return <div>Error: {error.message}</div>;
        } else if (!isLoaded) {
            return <div>Loading...</div>;
        } else {
            return (
              <ul>
                {quotes.map(quote => {
                    return quote;

                }  
                )}
              </ul>
            );
        }
    }
}       
    export default quotes;

I want to be able to display one object from the list of the array each time the page loads


Solution

  • It is failing because of CORS, which have to be included when different domains are handled by the server and client.

    CORS are included on the headers.

    Here's how you would enable corse in your react app:

    https://facebook.github.io/create-react-app/docs/proxying-api-requests-in-development

    CORS info:

    https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS