Mongoose Schemas

To be able to execute CRUD operations to interact with our database, we have to model our data. By this, we’ll create schemas that will be used to send data. In our example, we’ll create a document posting document details coming from Client and go to Server where the POST method will receive data and will grave it into the database, through our schema.

Read moreMongoose Schemas

Cross-origin resource sharing (CORS)

In this post, I’ll explain how to add HTTP headers to our requests. To send http requests to another domain, you have to add some headers to your requests. If you don’t have them, you probably will have this error message (click F12 on client for details).

XMLHttpRequest cannot load http://localhost:3000/subjects. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access.

CORS_DeveloperTools_error

Adding these lines to your HTTP Server configuration (ExpressJS for myLibrary project) you’ll be able to stablish communication between servers located in different domain. In this example we define permission to allow access to our Client that uses the port 9000, because the Server uses the port 3000.

    // CORS configuration
    // Allow-Origin
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:9000');
    res.setHeader('Access-Control-Allow-Credentials', true);
    res.setHeader('Access-Control-Allow-Methods', 'DELETE, PUT, GET, POST, OPTIONS, HEAD');
    res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, X-Powered-By');
    // Allow-Origin
 

Related Links

http://www.w3.org/TR/cors/

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