Introduction
In previous post (article), I created a Netlify function to return menu data in JSON format. In this post, I will show how to deploy the Netlify function to production environment and call the endpoint in the Angular Spanish Menu app from Github Page
Enable CORS in Netlify function
Github page and Netlify have different domain names, we must enable CORS in our Netlify function to ensure that it accepts HTTP request from any domain.
First, we modify netlify.toml to add HTTP header, Access-Control-Allow-Origin to specify allowed origins.
[[headers]]
# Define which paths this specific [[headers]] block will cover.
for = "/*"
[headers.values]
Access-Control-Allow-Origin = "*"
Deploy Netlify function to production
Second, we will deploy the function to production site such that our Angular app can access it in Github page.
- Login Netlify site
- Choose the site, navigate to Deploys menu and click Trigger deploy button to deploy the function manually
Update Angular environment variable
Third, we will update menuUrl variable in environment.prod.ts to point to the function at netlify.app.
export const environment = {
production: true,
menuUrl: 'https://<site name>.netlify.app/.netlify/functions/menu',
}
Deploy Angular to Github page
Next, we deploy our Angular app to Github page to verify integration with Netlify function actually works.
- Install angular-cli-ghpages.
ng add angular-cli-ghpages
- Add ng deploy configuration in angular.json
"deploy": {
"builder": "angular-cli-ghpages:deploy",
"options": {
"baseHref": "https://railsstudent.github.io/ng-spanish-menu/",
"name": "<user name>",
"email": "<user email>",
"message": "<github commit message>",
"repo": "https://github.com/railsstudent/ng-spanish-menu.git",
"noSilent": true
}
}
- Simplify deployment of our app by auhoring a new npm script
"github-page-deploy": "ng deploy"
npm run github-page-deploy
deploys our app to Github page on our behalf
Finally, we can browse our application to verify integration with the production Netlify function.
Verify integration
Browse https://railsstudent.github.io/ng-spanish-menu/food
Open Network tab to verify that our application calls menu function successfully. It is made possible because the value of access-control-allow-origin response header is “*”.
The result of the HTTP response is a valid JSON object containing our food menu.
Conclusion
We made few configuration changes and our Angular application can load data from the Netlify function.
This is the end of the post and I hope you find this article useful and consider to use serverless function to prototype Angular application.
Good bye!
Resources:
- Repo: https://github.com/railsstudent/ng-spanish-menu
- Github Page: https://railsstudent.github.io/ng-spanish-menu/food
- Access-Control-Allow-Origin Policy – https://answers.netlify.com/t/access-control-allow-origin-policy/1813/6
- https://www.netlify.com/blog/2021/01/25/getting-started-with-netlify-functions-for-angular/