Now, if we reload the page, fill in our details, and press the Register button, we'll encounter a CORS-related error. This is because our API server is currently only servicing requests from our Swagger documentation page (on http://localhost:8100); requests from other websites are rejected.
To resolve this, we need to provide the Hobnob API with information about the location of our client. We can do this by adding a few more environment variables. Add the following entries to the envs/.env and envs/.env.example files in our Hobnob API repository.
CLIENT_PROTOCOL=http
CLIENT_HOSTNAME=127.0.0.1
CLIENT_PORT=8200
Then, we need to add the client's origin to the list of origins our API should allow. We can do this by updating the CORS middleware to set the Access-Control-Allow-Origin header dynamically. Make the following change inside src/index.js of our Hobnob API repository:
app.use((req, res, next) => {
const {
SWAGGER_UI_PROTOCOL, SWAGGER_UI_HOSTNAME, SWAGGER_UI_PORT,
CLIENT_PROTOCOL, CLIENT_HOSTNAME, CLIENT_PORT,
} = process.env;
const allowedOrigins = [
`${SWAGGER_UI_PROTOCOL}://${SWAGGER_UI_HOSTNAME}`,
`${SWAGGER_UI_PROTOCOL}://${SWAGGER_UI_HOSTNAME}:${SWAGGER_UI_PORT}`,
`${CLIENT_PROTOCOL}://${CLIENT_HOSTNAME}`,
`${CLIENT_PROTOCOL}://${CLIENT_HOSTNAME}:${CLIENT_PORT}`,
];
if (allowedOrigins.includes(req.headers.origin)) {
res.setHeader('Access-Control-Allow-Origin', req.headers.origin);
}
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
next();
});
Lastly, coming back to our client application, we need to ensure that the client is serving at the port we specified, and also that CORS is enabled. We can do this simply by using the -p and --cors flag provided by the http-server package.
$ http-server . -p 8200 --cors
Now, if we reload both our API server and our client, and try to register, we should get back a success response.