#transfer data between components in vue
Explore tagged Tumblr posts
Text
Security and Performance: Key Considerations for Frontend Development Services in 2024
Tumblr media
In 2024, companies looking to build or improve their websites and apps need to prioritize security and performance. Choosing an experienced front end development agency is crucial to get this right. By leveraging modern frameworks and following best practices, developers can create fast, responsive experiences that protect user data. As threats and technologies evolve, continuously evaluating and upgrading frontend code is essential. Partnering with experts who stay on top of industry trends allows companies to keep their digital experiences safe while delighting customers.
Security Considerations
Security should be a top priority for any front-end development services today. Implementing SSL/HTTPS across all sites and pages is now a must to encrypt connections and data. Validating and sanitizing user inputs is also critical to prevent scripts or unauthorized commands being injected into applications.
Another key area is implementing protections against common attacks like cross-site request forgery (CSRF) and cross-site scripting (XSS). These can allow attackers to steal user data or authentication details. Following security best practices like the OWASP guidelines can help mitigate these risks.
Strong authentication mechanisms and authorization controls are also vital for securing the front-end against unauthorized access. Practices like multi-factor authentication, role-based access, and use of secure tokens can make user accounts highly secure.
In addition, front-end developers must ensure proper segregation between application layers, use parameterized queries, and implement robust logging and monitoring to detect potential threats and attempted attacks against the front-end.
Performance Considerations
There are many techniques front-end developers can use to optimize performance. Minification removes extra spaces and shortens variable names to make code lighter. Concatenation combines multiple files into one to reduce HTTP requests.
Lazy loading defers non-critical components and images from loading until needed. This speeds initial page load by reducing what needs to be fetched first. Implementing caching strategies also avoids re-downloading assets on repeat views.
Critical CSS/JS extracts only the CSS/JS needed for above-the-fold content. This renders the visible page faster. Compression using gzip shrinks file sizes for faster transfers.
Performance testing tools help identify bottlenecks. Common optimizations include using CDNs, optimizing images, eliminating render blocking resources, and removing unused code.
Progressive enhancement and graceful degradation also improve performance. They ensure core content loads quickly while modern features enhance the experience on capable browsers.
Continued performance testing and optimization is key for ensuring fast, smooth front-end experiences over time.
Frontend Frameworks and Security
Modern frontend frameworks like React, Vue, and Angular all have robust security features built-in or available as plugins. While their core libraries are secure, how developers use them also impacts security.
React offers protection against common attacks like XSS and cross-site script inclusion with features like JSX encoding. Additional security addons are also available.
Vue provides cross-site scripting protection by encoding bindings and interpolations. Authentication plugins help securely manage user access.
Angular has strong CSRF defenses built-in. It also sanitizes inputs to prevent XSS. Authorization controls secure access to routes and resources.
Ember.js automatically escapes Handlebar templates to prevent XSS. It also has security addons like ember-simple-auth for authentication.
Overall, popular frameworks provide good security foundations. But developers must use them properly, add security layers, and keep them updated to leverage their benefits.
Emerging Security Trends
Security is an ongoing challenge in frontend development. As new vulnerabilities emerge, practices and tools must evolve to address them.
Some key trends gaining traction are shifting security left, DevSecOps, and automated testing. Building in security from initial design phases reduces costs and results in more secure systems. DevSecOps integrates security into development workflows for speed and quality. Automated tools help efficiently scan for and fix vulnerabilities early.
Shift left security involves developers, architects and security experts collaborating from the beginning of projects. This results in more secure foundations.
DevSecOps aims to bring security, development and operations together with shared tools, practices and culture. This enables speed without sacrificing security.
Automated scanning and testing tools at each phase quickly catch vulnerabilities without relying solely on human review.
Lightweight protection layers like web application firewalls help defend against threats without slowing performance.
AI and machine learning are being utilized for adaptive cybersecurity defense and attack prevention.
Emerging Performance Trends
Optimizing performance will remain crucial for front-end developers as user expectations grow. New metrics, protocols and patterns are emerging to help build faster experiences.
Some key trends include a focus on user-centric performance metrics like Largest Contentful Paint and Cumulative Layout Shift. HTTP/3 and QUIC aim to speed up transfer times. PRPL and service workers cache or preload resources for snappier loading.
Core web vitals like LCP, CLS and TTI provide user-centric performance metrics beyond speed alone.
HTTP/3 with QUIC protocol features multiplexing and congestion control for faster page loads.
The PRPL pattern aims to Push critical resources, Render initial views, Pre-cache remaining assets, and Lazy-load other routes.
Service workers allow caching site assets like JavaScript, CSS, images, and HTML for instant loading on return visits.
New frameworks like Svelte aim to build high performance into components with a low-overhead design.
More bundlers and build tools now focus on optimizing assets and splitting code for lazy loading parts.
Conclusion
As frontend development continues to evolve, keeping pace with security and performance best practices will be key for agencies to deliver excellent services. By making security a priority throughout the development lifecycle, utilizing emerging DevSecOps practices, and leveraging automated testing tools, frontend code can be made highly secure. Performance should also be optimized through techniques like lazy loading, HTTP/3 adoption, and a focus on core web vitals. As new technologies and methodologies emerge, developers must stay up-to-date to balance seamless user experiences with robust security. Keeping these considerations central in 2024 and beyond will ensure frontend services provide fast, smooth, and secure experiences that users have come to expect.
0 notes
laravelvuejs · 5 years ago
Photo
Tumblr media
Transfer Data Between Components In Vue JS How you can transfer data between components in vue js? I'll explain to you the communication between a parent component and a child component. source
0 notes
t-baba · 6 years ago
Photo
Tumblr media
Preact X, Node-RED 1.0, and TypeScript 3.7 beta
#457 — October 4, 2019
Read on the Web
JavaScript Weekly
Tumblr media
Preact X: A Fast, 3KB React Alternative — Two years in the making, the latest version of Preact, a popular lightweight React-compatible alternative, is here. Support for hooks, ‘fragment’ components, and improved error handling are all here. For more info, check out the What’s new in Preact X guide.
Preact
The Differences Between the Same App Created in React and Vue — An interesting side by side comparison of the same app built by the same developer in both React and Vue.js. If you’ve seen this post before, it’s just been rewritten and updated to use React hooks.
Sunil Sandhu
🔒 Build an Encrypted File Transfer in 15 Minutes — Tanker.io helps you secure data exchanges in your apps. Encrypt, upload and share files in one API call, in the browser. No key management, zero crypto skills required.
Tanker sponsor
Creating Custom JavaScript Syntax with Babel — Wow, this is cool. An introduction to forking Babel and creating your own custom JavaScript syntax.
Tan Li Hau
Evaluating JavaScript Code via import() — import lets us dynamically load modules but can also work as a sort of alternative to eval.. an interesting trick here.
Dr. Axel Rauschmayer
Node-RED 1.0 Released — Node RED is a flow-based, visual programming tool (aimed primarily at hardware automation) that’s built on top of Node.js. Despite only reaching 1.0 now, it’s a mature project used in numerous real world IoT projects.
Nick O'Leary
Quick bytes:
Meteor, the JavaScript app platform, has been acquired by Tiny, the owners of Dribbble and Designer News.
TypeScript 3.7 beta is here. It implements a much demanded feature: optional chaining.
💻 Jobs
JavaScript Developer at X-Team (Remote) — Work with the world's leading brands, from anywhere. Travel the world while being part of the most energizing community of developers.
X-Team
Your Princess (or Prince!) IS in this Castle: Node Developer (London) — This role is for a senior JS/Node/React dev who can’t wait to tackle more architectural responsibility at a large, well-known company with a passion for saving folks money.
CareersJS
Find A Job Through Vettery — Vettery specializes in tech roles and is completely free for job seekers. Create a profile to get started.
Vettery
📘 Articles & Tutorials
How to Build Cross-Platform, Native Desktop Apps with NodeGUI — A beginner’s guide to NodeGUI, a tool for building native desktop applications with JavaScript and CSS styling in a more lightweight way than using Electron.
James Hibbard
How V8 Is Improving V8 Regular Expressions — This is very technical, JavaScript engine-y sorta stuff, but basically the V8 team show off their technique for speeding up how regexes are interpreted.
Patrick Thier and Ana Peško (V8)
Free Webinar on User Journey Testing with Scott Davis from ThoughtWorks
Gauge sponsor
How to Build a Progressive Web App (PWA) with only Vanilla JS — Bring a native-like experience to your webapps with this grab bag of techniques including styling, fonts, Service Workers, and creating a manifest file.
Sayan Mondal
Don't Use Variables Without Knowing About the 'Temporal Dead Zone' — In short, don’t use anything before declaring it.
Dmitri Pavlutin
Don't Sync State, Derive It — Avoid synchronization bugs and hidden complexity by deriving (or calculating) state in React apps on the fly rather than keeping numerous copies of state around your app.
Kent C Dodds
▶  Let's Build a 16-Bit Virtual Machine in JavaScript — This is a ‘rabbithole which goes really deep’ warns Francis, but you’ll learn a lot of interesting things along the way.
Low Level JavaScript
BLOG: JavaScript Project Configuration — Check out our full list of JavaScript blog posts.
Big Nerd Ranch sponsor
'How I Stopped Worrying and Learned to Love the JavaScript Ecosystem' — Sometimes you have to take a step back and think about what really matters.
Flavio Copes
🔧 Code & Tools
Carbon: Create Beautiful Images of Your Source Code — We’re huge fans of seeing code snippets shared on social media and while images do have accessibility issues, they remain a rapid-fire way to get code into a tweet or Instagram image and Carbon excels at the task.
Carbon
SweetAlert2: Responsive, Customizable and Accessible Popup Boxes — An attractive and accessible (WAI-ARIA) replacement for native popup boxes with zero dependencies.
SweetAlert2
The Most Complete Spreadsheet Solution for JavaScript Apps - SpreadJS — Fast enterprise JavaScript spreadsheet for delivering true Excel-like spreadsheet experiences. Download free eval.
SpreadJS by GrapeCity sponsor
Tribute: A Library for Handling @mentions — If you have text fields, in which other users might be cited, this could be handy. Check out the demo page.
ZURB
Cropper.js: An Image Cropping Control — A mature project but continuing to get frequent releases.
Chen Fengyuan
Revocable Queue: Specialized Async Queue Data Structure — Asynchronously and lazily read/write values to a queue, from which you can also revoke yet-unread values.
Kyle Simpson
⚡️ Quick Releases
React 16.10
Create React App 3.2.0 — The quickest way to get started with React.
Nuxt 2.10 — Framework for building universal Vue apps.
Bluebird 3.7 — Popular promises library.
Greenlet 1.1 — Move async functions into their own threads.
Bowser 2.7 — Browser detection library.
🐦 Over on Twitter...
Tumblr media
by via JavaScript Weekly https://ift.tt/2oTj0Gq
0 notes
flatlogic · 4 years ago
Text
How to Choose the Best React Drag and Drop? Top 15 Free Libraries to Set Up
New Post has been published on https://flatlogic.com/blog/how-to-choose-the-best-react-drag-and-drop-top-15-free-libraries-to-set-up/
How to Choose the Best React Drag and Drop? Top 15 Free Libraries to Set Up
What is Drag and Drop? Drag and Drop types Basic Concepts How to choose the Drag and Drop?  Typescript vs Javascript How to build a custom React Draggable Component? How do I drag and drop in React dnd? React Drag and Drop Library List Wrapping Up About Flatlogic
User experience is crucial when you interact with your website or web app. Though it may seem that choosing a drag and drop element is no big deal, after all, it’s just a basic functionality component! But, the drag and drop module lets you transfer the items between drag handlers, tables and lists, touch devices, animations, previews, and placeholders, thus resolving the simple but still integral step that allows you to ‘take an object’ and drag it to another location.
What is Drag and Drop?
Drag and drop is an action carried out by the user in order to move one or another element to a different place in UI. There are lots of well-known applications where you use the drag and drop function as the basic one, let’s remind ourselves of just a few of them: Trello, Jira, Zapier, Monday, and others, where we one way or another using drag and drop to move things.
This simple action may be comfy not only as a part of the modern user experience, especially for those people who have disabilities or some difficulties with performing manual-type actions.
But why does such a simple element take quite a while to develop? The answer is simple: it takes a lot of code to build high-quality, neat and clean JavaScript forms. And it is much faster to run any ready-made library where you can easily borrow some pieces of code.
Check out React Material Admin Full!
Material UI No jQuery and Bootstrap! Fully Documented Codebase
Drag And Drop Types
There are dozens of open-source libraries that help to create draggable and movable elements (e.g. lists, cards, tables, etc) in your React app. And, this option can simplify the UX route, in comparison to the process of filling in forms, and shortens the time of one or another formal action.
The most common use cases for drag-and-drop in React include: uploading files; replacing the components within created lists and rearranging images and assets.
Basic Concepts
DragDrop Container: where you held and then taken out the component (data)
Children: the content of dataItem; DragDropContext: is the place where drag-and-drop is carried out;
Droppable: the component which allows draggable components to be able to drop at the targeted area;
Draggable: the component which will be replaced;
As well as Droppable, it requires several properties to make the component displaceable;
onDragStart: onDragStart component occurs when the user starts to drag an element;
onDragEnd: the component known as DragEnd occurs after the action has been accomplished;
DataTransfer: the component that can hold data about the dragged object;
DropTarget: component that contains drop data;
How to Choose a Good Drag and Drop?
Surely, this is a relatively controversial question, because if you have enough time at your disposal, you may start coding on your own. Moreover, if you’re a junior programmer, we would not recommend that you use any ready libraries, but try to figure out the problem using your own code. Yes, bugs are inevitable, though after each challenge there will surely be progress.
In Flatlogic we create web & mobile application templates built with React, Vue, Angular and React Native to help you develop web & mobile apps faster. Go and check out yourself! See our themes!
Typescript vs. Javascript Library
The vast majority of drag and drop libraries are written with the help of Typescript prevalence because Typescript is known for being structured, highly secure, and more consistent than vanilla Javascript. At the same time, it takes longer to compile the code in TypeScript, whereas JavaScript is more easy and flexible in terms of development.
Do you like this article? You can read also:
React Pagination Guide And Best React Pagination Libraries
So, if you are an old-school adherent, who is devoted to JS, you should understand that you need to know Typescript peculiarities to write with it. Plus, the size of the code will increase,  because Typescript requires extremely detailed and accurate coding.
How to Build Custom Draggable Components in React?
To enable dragging on the component we need to proceed this path:
First off, create a drag component (drop area), in other words — container, where you will further drag dataItem. Set the draggable attribute on the dataItem
Handle onDragStart event Add here event.dataTransfer.setData 
event.dataTransfer.setData  component will contain some data, dataItem Create a function startDrag event Create a dropTarget component; it will call an event handler when dataItem with children will be dropped in Handle onDragOver event Create event.preventDefault() function that will enable the dropping process of the component Handle onDrop event Set the consent function – getData
Call the dropped component onItemDropped
Finally, return the components to their initial state,  
<div onDragOver=dragOver onDrop=drop>  props.children </div>);
Voila! This way your component will be ‘transferred’ from the container to the DropTarget.
How to Make Drag and Drop With React dnd library?
React Drag’n’Drops Libraries List
1. React Beautiful Dnd
React beautiful dnd is the most popular library to build React Drag and Drop lists easily. It has already won the heart of 23.8k developers on GitHub, thanks to its high performance. It has a clean and powerful API that is easy to work with and it fits well with any modern browser.
GitHub
2. React Drag and Drop Container
Here the name of the library speaks for itself. React Drag Drop container offers functionality for mouse and touch devices; i.e. it allows you to set up a draggable element, drop a target for it, plus, it highlights the drop target when dragging over it (highlightClassName). Also, you can drag an element copy of the element, or let the element disappear while dragging (disappearDraggedElement).
GitHub
3. Draggable
Another well-deserved library, does not perform any sorting behaviour while dragging, it has the following modulers: Droppable, Sortable, and Swappable. Draggable itself does not perform any sorting behaviour while dragging, but does the heavy lifting, e.g. creates mirror, emits events, manages sensor events, makes elements draggable.
GitHub
4. React Grid Layout
React Grid Layout library has 13,5k stars on GitHub. Inside you will get a fluid layout with sensible breakpoints, static widgets, draggable and resizable widgets. You can drag the elements, and resize them. The closest similar instrument is called Packery, though this is a bin-packing layout library using jQuery, which React Grid Layout doesn’t use.
: React-Grid-Layout works well with complex grid layouts that require drag-and-drop, such as dashboards which can be resized(e.g., looker, data visualization products, etc.)
: Because of the clunky API, React-Grid-Layout may need more calculations and it’s obviously a better fit for large-scale apps.
5. React Dropzone
React Dropzone is an example of simple HTML5 drag and drop zone with React.js. It requires a standard installation process with npm command and using a module bundler like Webpack or Browserify. React Dropzone has  8.2  Github stars and is based on Javascript.
GitHub
6. React DND
React DND got 15.9k stars on GitHub, and was written mainly with the help of  TypeScript, as well as JavaScript and CSS. It has the sort option, group option, delay option, delayOnTouchOnly option, swapThreshold option, and many other essential features for implementing drag and drop components. React DND works well with grids, one-dimensional lists, but it’s harder to work with than for instance the well-known react-beautiful-dnd when you need to customize something individually.
GitHub
7. React SortableJS
React sortable is one more brilliant instrument made with Javascript and HTML, commonly used for creating drag-and-drop lists. It has all the basic functionalities of sorting/delaying/swapping/inverting and lots of others. Available on all touch modern browsers and touch devices.
GitHub
8. Interact.js
Snap, resize, customize your drag and drop elements with Interact.js. The library has also an advanced version, check it here. It also supports evoking simultaneous interactions; interaction with SVG and works well with desktop and mobile versions of Chrome, Firefox, and Opera as well as Internet Explorer 9+. Sharp has 10.2 k on GitHub and
GitHub
9. React Kanban
React Kanban is a relatively young but super pluggable library positioning itself as ‘one more Kanban/Trello board lib for React’. Kanban was written with the help of JavaScript, SCSS and HTML. But, be careful using this library with lots of cards (more than 1k), cause then you may face some performance hurdles. In this case, virtual lists may become the solution.
GitHub
10. Juggle and Drop
Juggle and Drop is an instrument to manage your tasks made with pure Javascript, with the help of React, redux, MLAB, express mongodb, Google Analytics. With Juggle and Drop you can add, edit, delete cards and lists; clone the component, navigate to the root directory, and other.
GitHub
11. React Motion
One more highly recommended and really powerful package for working with animation functions in JS. This package has 19.7k on GitHub, and 612,446 installations according to NPM. And among others, it has sorting lists with drag and drop. How to get started? npm install — save react-motion and keep working!
GitHub
12. React Smooth DnD
The React-smooth drag and drop package is a super lightweight and highly customizable library for React with 1,5k stars on GitHub and with lots of configuration options covering d&d scenarios. The cardboard and fonts look really neat and pleasant to the eye.
GitHub
13. Nested DND
Nested DND in juicy colors helps to drag a part of the stack with the items lying on top of the dragged one. Drop it on top of any plays, and see how simple and intuitive it is.
GitHub
14. React Nestable
React Nestable, an example of JavaScript drag and drop library, is a drag & drop hierarchical list made with a neat bit of deduction. This package is finalizing our list of open-source drag and drop libraries recommended while building the dnd option.
GitHub
15. React Files Drag and Drop
One more relatively fresh library to manage and customize your inner drag and drop component easily is React-files-drag-and-drop. It has a list of basic properties and was developed with TypeScript and CSS language.
GitHub
Check more examples of React drag and drop on codesandox or here.
Wrapping Up
Now you know enough about React DnD libraries and it is high time to explore further the rest of the documentation in detail! Stay motivated, don’t be afraid of making mistakes, and debugging them! Well, this is a good place to tell: if you’ve never made a mistake,  you’ve probably never done anything.
About Flatlogic
At Flatlogic, we carefully craft dashboard templates on React, Vue, Bootstrap and React Native to bootstrap coding. We are mentioned in the Clutch top-performing agencies from all over the world. In the last 6 years, we have successfully completed more than 50 templates and large-scaled custom development projects for small startups and large enterprises. We love our work and know that only beauty (beautifully designed templates 🙂 ) can save the world.
Suggested Posts:
Top 30 Open Source And Paid React Charts + Examples React Table Guide And Best React Table Examples Best React Open Source Projects
The post How to Choose the Best React Drag and Drop? Top 15 Free Libraries to Set Up appeared first on Flatlogic Blog.
1 note · View note
mojomediapro · 6 years ago
Text
Full-Stack Web Developer: Web Development Learning Guide
This is a comprehensive guide to everything you need to know on your way to becoming a professional web development. Web development is a process of many steps from the idea to a professional web site. Let’s start with the roadmap that we are going to take.
Start: Identify the basic tools.
Station 1: Web Design Tools and Languages.
Station 2: Site programming tools and languages.
Last stop: Developer tools.
The beginning of the journey – the basic tools for website design
Browser: The web developer who specializes in the design of the site needs the browser almost always, where it is used to experience the site during the design process and the most important and most famous browsers for good designers: Google Chrome & Firefox. Chrome is the most popular browser between them despite the potential of the Firefox browser.
Editor: A tool needed by the site designer and the programmer specialized in the server, and some more helpful programs provide add-ons for programming to facilitate the writing and understanding of programs and the most famous editors: VS Code, Atom, WebStorm, etc. All of them are powerful and convenient for web development, but the most common among them is VS Code.
Design program: The developer may need a design program to design the components of the site. Adobe has launched a program Adobe XD specializes in designing websites and mobile applications.
  The first stop – Front-end website design
In the first stop we will stop at the details of building the front-end design of the site and its ability to interact with users, as well as being proportional to all their devices and build everything the site needs from the user side, and to do this we start to learn several things and the steps are as follows:
Step One – the basics of HTML / CSS design
Beginners often learn the basics together, as the developer builds the elements of the interface via HTML and then arranges them and adds some aesthetic through CSS, and can not proceed with web development without a good foundation.
Here are some important points to be mastered in this step:
Semantics of HTML5 elements.
Basics of ordering items using CSS3.
Web within the web page and Flexbox properties.
Transformations in CSS.
Use browser development tools.
Step Two – Build a Responsive Design
After learning the principles of building a web page and having sufficient knowledge in the basics of design, the developer should learn to build a website compatible with all devices and screens, which is called Responsive Design, which is necessary for building any website, including knowledge of several points, including:
Viewport organization.
Flexible build the fluid display to suit any device.
Organize media elements (photos and videos).
Use relative units such as rem to improve the appearance of the site on various devices.
The design is compatible with the mobile besides the computer.
Step Three – Programming Design
Whatever the way you will go later in the development of the site it is very important to learn the programming language JavaScript , it is the basis for adding dynamism of the site and programming by the user, which is the basis of any programming framework for the design of the site and is available in the programming of the server as we will soon know, so we must know the basics of the language Javascript as the first programming language in the development of sites, here are some points due to know:
Data types, dependencies, conditions, loops, and transactions.
Understand the communication process between JS and HTML and a good understanding of DOM and events.
Knowledge of data modulation methods such as JSON and XML.
How to send requests online.
Advanced concepts at JS include arrow-related functions, promises, and the most famous ES6 concepts.
Step Four – Know the basics of jQuery
jQuery is a very rich and famous JavaScript library, which makes it easy to handle HTML files and interface elements within them, as well as being compatible with all browsers. It is not separate from JavaScript, but it helps in some programming processes that require writing a lot in Java Script is not for its existence much easier in jQuery.
Step Five – Know the basics of Ajax
Ajax is an acronym for (Asynchronous JavaScript and XML), a Web technology that can update the web pages asynchronously through data exchange with the server without having to refresh the page, which is flexible so that the entire web page content change without updating the most famous examples of the suggestions Google that appear In the search box when we start typing.
Step Six – Use Sass
Sass, or known as an advanced CSS handler, allows you to manipulate transformers, use input instructions, some rules, and some other instructions, as well as organize the appearance of properties further, helping to make CSS easier and more flexible.
Step Seven – Use the JS framework
It is no longer prevalent to build sites without the use of frameworks that fit the need of the site and to choose the appropriate framework for the site to know the options available, perhaps the most famous frameworks are:
Angular Framework: A framework introduced by Google to facilitate the work of developers, based on HTML and Javascript / TypeScript languages, combines the templates and components based on each other and provides the best ways to build a site that can be maintained and developed in line with advanced technologies.
Vue framework: Vue library is one of the easiest libraries in terms of learning, has flourished recently, and is a suitable framework for small projects and single-page sites, and can very quickly learn and apply and enjoy the results, and in fact, large companies began to use more and increased desire to hire Vue experts.
 Here you can call yourself Front-End Developer and get a job.
Second Station – Back-end Programming
The web developer journey continues after completing different skills and reaching the stage of the front-end developer.
The first step – Server Programming Languages
PHP: One of the most popular languages ​​around the world dedicated to server programming, and more than half of the sites and services that we find on the Internet are written in PHP language.
Node.js : Here you can program the server using the JavaScript language that we used earlier in the design of the site, and this point makes the development using Node.js one of the most popular methods currently, so if you want to learn a new language in the development, you have to choose Node.js.
Python: Python can be used to program the server, one of the important and powerful languages ​​in the programming of the server around the world.
The second step – the use of frameworks
As in the design of the site, no one would like to rebuild the engine from scratch, so we are going to use some famous frameworks to accelerate and facilitate the work of programming, including:
Django Framework: The most famous Python language framework, which helps organize and arrange software files and facilitates work.
Laravel Framework: The most powerful framework for PHP Although there are other options like Symfony, Laravel is the most popular.
Express window: It’s the most commonly used frame with Node.js, and if you decide to use it you should take a look and try it.
The third step – Databases
MySQL: It is the most used for relational databases, the most popular classical type among database types and we add it PostgreSQL and MS SQL.
MongoDB: It is the most popular type of non-SQL-based database or so-called NoSQL.
One last stop – tools and concepts of interest to developers
The concept of MVC (Model-View-Controller) that accompanies most software frameworks.
HTTP / HTTPS concepts and everything related to Internet security.
Programs within the server Apache and xampp that make the server capable of running software files.
Site SEO compatibility with any search engines, where the site is built within certain criteria to improve visibility in the search results.
Software dealing with files within the server and the transfer mechanism of the server such as Filezilla.
Here the developer can say that you are Full Stack Developer and get your dream job as a professional web developer. It must be noted that the tools and software mentioned are constantly changing and the developer should follow the new tools.
The post Full-Stack Web Developer: Web Development Learning Guide appeared first on MojoMedia.Pro.
from MojoMedia.Pro https://www.mojomedia.pro/full-stack-web-developer-web-development-learning-guide/
0 notes
programmingbiters-blog · 7 years ago
Photo
Tumblr media
New Post has been published on https://programmingbiters.com/codeigniter-restful-web-services-codexworld/
CodeIgniter RESTful Web Services - CodexWorld
youtube
Representational state transfer (REST) or RESTful web services provide a way to exchange data between applications or systems on the Internet. RESTful web service also refers as RESTful API, uses HTTP request to GET, PUT, POST and DELETE data across platforms. In present days, RESTful API is an essential component of the web application.
When the CodeIgniter application requires communicating with another application, RESTful API is needed to integrate into CodeIgniter. Using RESTful API in CodeIgniter, you can exchange data between different applications or platform. This tutorial shows RESTful server implementation for CodeIgniter and you will learn how to create RESTful web services in CodeIgniter.
If you are beginners to CodeIgniter, first see CodeIgniter from Scratch tutorial to setup and configure CodeIgniter application.
To demonstrate CodeIgniter REST API, we will implement CRUD operations in CodeIgniter web service. The following tasks will be performed to create a simple REST API in CodeIgniter.
Setup RESTful library for CodeIgniter.
Create API method to fetch the user information via GET request.
Create API methods to add, edit, and delete user information via POST, PUT, and DELETE request.
Interact with the CodeIgniter Rest API using PHP cURL.
Test HTTP calls with Google Chrome Postman extension.
Before you get started, take a look the files structure of CodeIgniter REST API.
Create Database Tables
To store user’s information, a table needs to be created in the database. The following SQL creates a users table with some basic fields in MySQL database.
CREATE TABLE `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `first_name` varchar(100) COLLATE utf8_unicode_ci NOT NULL, `last_name` varchar(100) COLLATE utf8_unicode_ci NOT NULL, `email` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `phone` varchar(20) COLLATE utf8_unicode_ci NOT NULL, `created` datetime NOT NULL, `modified` datetime NOT NULL, `status` enum('1','0') COLLATE utf8_unicode_ci NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
The following SQL creates a keys table to store REST API key for authentication.
CREATE TABLE `keys` ( `id` int(11) NOT NULL AUTO_INCREMENT, `user_id` int(11) NOT NULL, `key` varchar(40) NOT NULL, `level` int(2) NOT NULL, `ignore_limits` tinyint(1) NOT NULL DEFAULT '0', `is_private_key` tinyint(1) NOT NULL DEFAULT '0', `ip_addresses` text, `date_created` datetime NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Now insert an API key in keys table, which will be used on API call.
INSERT INTO `keys` (`id`, `user_id`, `key`, `level`, `ignore_limits`, `is_private_key`, `ip_addresses`, `date_created`) VALUES (1, 0, 'CODEX@123', 0, 0, 0, NULL, '2017-10-12 13:34:33');
CodeIgniter REST Controller Setup
We will use CodeIgniter REST_Controller to build RESTful web services in CodeIgniter. Follow the below steps to setup REST Controller Library in your CodeIgniter application.
Download REST config file and place in the application/config/ directory. Open the application/config/rest.php file and setup the following configuration.
Download REST_Controller file and place in the application/libraries/ directory.
Download Format class file and place in the application/libraries/ directory.
Download Language file and place in the application/language/english/ directory.
Note that: All the required library files are included in our example CodeIgniter application, so, you don’t need to download these files separately. Download our source code to get sample CodeIgniter RESTful Web service application.
Create Model
Open the application/models/ directory and create User.php file and add the following code to handle the database related works. The User model has the following methods to fetch, insert, update, and delete user data in the database.
__construct() – Load the database library.
getRows() – Fetch the user data from the users table and returns single row or multiple rows.
insert() – Insert user data in the users table.
user_put() – Update user data in the users table based on the given ID.
user_delete() – Delete user from the users table based on the given ID.
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class 
User extends CI_Model 
    public function 
__construct()          parent::__construct();                  //load database library         $this->load->database();     
    /*      * Fetch user data      */     function getRows($id = "")         if(!empty($id))             $query = $this->db->get_where('users', array('id' => $id));             return $query->row_array();         else             $query = $this->db->get('users');             return $query->result_array();                        /*      * Insert user data      */     public function insert($data = array())          if(!array_key_exists('created', $data))             $data['created'] = date("Y-m-d H:i:s");                  if(!array_key_exists('modified', $data))             $data['modified'] = date("Y-m-d H:i:s");                  $insert = $this->db->insert('users', $data);         if($insert)             return $this->db->insert_id();         else             return false;                        /*      * Update user data      */     public function update($data, $id)          if(!empty($data) && !empty($id))             if(!array_key_exists('modified', $data))                 $data['modified'] = date("Y-m-d H:i:s");                          $update = $this->db->update('users', $data, array('id'=>$id));             return $update?true:false;         else             return false;                        /*      * Delete user data      */     public function delete($id)         $delete = $this->db->delete('users',array('id'=>$id));         return $delete?true:false;     
?>
Create API Controller
It’s always a good idea to group all API controllers in a separate folder for better usability. So, create an api/ folder in application/controllers/ directory to place the controller which will be used for API call. Open the application/controllers/api/ directory and create Example.php file. At first, include the REST Controller library and add the following code. The Example API controller has the following methods to handle the GET, POST, PUT, and DELETE request.
__construct() – Load the User model.
user_get() – Return the user data from database. If the ID parameter doesn’t exist, it returns all the rows otherwise single row will be returned.
user_post() – Add user data to the database.
user_put() – Update the user data in the database based on the ID.
user_delete() – Delete the user from the database based on the ID.
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');//include Rest Controller library require APPPATH . '/libraries/REST_Controller.php';
class 
Example extends REST_Controller 
    public function 
__construct()           parent::__construct();                  //load user model         $this->load->model('user');               public function user_get($id = 0)          //returns all rows if the id parameter doesn't exist,         //otherwise single row will be returned         $users = $this->user->getRows($id);                  //check if the user data exists         if(!empty($users))             //set the response and exit             $this->response($users, REST_Controller::HTTP_OK);         else             //set the response and exit             $this->response([                 'status' => FALSE,                 'message' => 'No user were found.'             ], REST_Controller::HTTP_NOT_FOUND);                        public function user_post()          $userData = array();         $userData['first_name'] = $this->post('first_name');         $userData['last_name'] = $this->post('last_name');         $userData['email'] = $this->post('email');         $userData['phone'] = $this->post('phone');         if(!empty($userData['first_name']) && !empty($userData['last_name']) && !empty($userData['email']) && !empty($userData['phone']))             //insert user data             $insert = $this->user->insert($userData);                          //check if the user data inserted             if($insert)                 //set the response and exit                 $this->response([                     'status' => TRUE,                     'message' => 'User has been added successfully.'                 ], REST_Controller::HTTP_OK);             else                 //set the response and exit                 $this->response("Some problems occurred, please try again.", REST_Controller::HTTP_BAD_REQUEST);                      else             //set the response and exit             $this->response("Provide complete user information to create.", REST_Controller::HTTP_BAD_REQUEST);                        public function user_put()          $userData = array();         $id = $this->put('id');         $userData['first_name'] = $this->put('first_name');         $userData['last_name'] = $this->put('last_name');         $userData['email'] = $this->put('email');         $userData['phone'] = $this->put('phone');         if(!empty($id) && !empty($userData['first_name']) && !empty($userData['last_name']) && !empty($userData['email']) && !empty($userData['phone']))             //update user data             $update = $this->user->update($userData, $id);                          //check if the user data updated             if($update)                 //set the response and exit                 $this->response([                     'status' => TRUE,                     'message' => 'User has been updated successfully.'                 ], REST_Controller::HTTP_OK);             else                 //set the response and exit                 $this->response("Some problems occurred, please try again.", REST_Controller::HTTP_BAD_REQUEST);                      else             //set the response and exit             $this->response("Provide complete user information to update.", REST_Controller::HTTP_BAD_REQUEST);                        public function user_delete($id)         //check whether post id is not empty         if($id)             //delete post             $delete = $this->user->delete($id);                          if($delete)                 //set the response and exit                 $this->response([                     'status' => TRUE,                     'message' => 'User has been removed successfully.'                 ], REST_Controller::HTTP_OK);             else                 //set the response and exit                 $this->response("Some problems occurred, please try again.", REST_Controller::HTTP_BAD_REQUEST);                      else             //set the response and exit             $this->response([                 'status' => FALSE,                 'message' => 'No user were found.'             ], REST_Controller::HTTP_NOT_FOUND);                 ?>
Interacting with CodeIgniter RESTful Web Services
Now it’s time to interact with the CodeIgniter RESTful Web Services. The cURL is the most flexible and easiest way to interact with a REST API. In the following example code, we will show you how to send GET, POST, PUT and DELETE request to CodeIgniter REST API using PHP cURL. Also, HTTP Basic authentication and API key will be used to connect with RESTful API.
Retrieve User Data via REST API The following code performs a GET request to fetch the user data via RESTful Web Services (Example API).
//API URL $url = 'http://localhost/codeigniter/api/example/user/';//API key $apiKey = 'CODEX@123';//Auth credentials $username = "admin"; $password = "1234";//create a new cURL resource $ch = curl_init($url);curl_setopt($ch, CURLOPT_TIMEOUT, 30); curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY); curl_setopt($ch, CURLOPT_HTTPHEADER, array("X-API-KEY: " . $apiKey)); curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");$result = curl_exec($ch);//close cURL resource curl_close($ch);
Insert User Data via REST API The following code performs a POST request to insert user data via RESTful Web Services (Example API).
//API URL $url = 'http://localhost/codeigniter/api/example/user/';//API key $apiKey = 'CODEX@123';//Auth credentials $username = "admin"; $password = "1234";//user information $userData = array(     'first_name' => 'John',     'last_name' => 'Doe',     'email' => '[email protected]',     'phone' => '123-456-7890' );//create a new cURL resource $ch = curl_init($url);curl_setopt($ch, CURLOPT_TIMEOUT, 30); curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY); curl_setopt($ch, CURLOPT_HTTPHEADER, array("X-API-KEY: " . $apiKey)); curl_setopt($ch, CURLOPT_USERPWD, "$username:$password"); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $userData);$result = curl_exec($ch);//close cURL resource curl_close($ch);
Update User Data via REST API The following code performs a PUT request to update user data via RESTful Web Services (Example API).
//API URL $url = 'http://localhost/codeigniter/api/example/user/';//API key $apiKey = 'CODEX@123';//Auth credentials $username = "admin"; $password = "1234";//user information $userData = array(     'id' => 2,     'first_name' => 'John2',     'last_name' => 'Doe2',     'email' => '[email protected]',     'phone' => '098-765-4321' );//create a new cURL resource $ch = curl_init($url);curl_setopt($ch, CURLOPT_TIMEOUT, 30); curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY); curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-API-KEY: '.$apiKey, 'Content-Type: application/x-www-form-urlencoded')); curl_setopt($ch, CURLOPT_USERPWD, "$username:$password"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($userData));$result = curl_exec($ch);//close cURL resource curl_close($ch);
Delete User Data via REST API The following code performs a DELETE request to delete user data via RESTful Web Services (Example API).
//API URL $url = 'http://localhost/codeigniter/api/example/user/2';//API key $apiKey = 'CODEX@123';//Auth credentials $username = "admin"; $password = "1234";//create a new cURL resource $ch = curl_init($url);curl_setopt($ch, CURLOPT_TIMEOUT, 30); curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY); curl_setopt($ch, CURLOPT_HTTPHEADER, array("X-API-KEY: " . $apiKey)); curl_setopt($ch, CURLOPT_USERPWD, "$username:$password"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');$result = curl_exec($ch);//close cURL resource curl_close($ch);
Test HTTP calls with Postman Extension
Postman Extension makes API development faster, easier, and better. Install Postman Extension for testing the API call.
Are you want to get implementation help, or modify or extend the functionality of this script? Submit paid service request
0 notes
t-baba · 7 years ago
Photo
Tumblr media
How to Deploy Your Secure Vue.js App to AWS
This article was originally published on the Okta developer blog. Thank you for supporting the partners who make SitePoint possible.
Writing a Vue app is intuitive, straightforward, and fast. With low barriers to entry, a component-based approach, and built-in features like hot reloading and webpack, Vue allows you to focus on developing your application rather than worrying about your dev environment and build processes. But, what happens when you are ready to deploy your app into production? The choices can be endless and sometimes unintuitive.
As an AWS Certified Solutions Architect, I am frequently asked how to deploy Vue apps to AWS. In this tutorial, I will walk you through building a small, secure Vue app and deploying it to Amazon Web Services (AWS). If you’ve never used AWS, don’t worry! I’ll walk you through each step of the way starting with creating an AWS account.
About AWS
Amazon Web Services (AWS) is a cloud platform that provides numerous on-demand cloud services. These services include cloud computing, file storage, relational databases, a content distribution network, and many, many more. AWS came into existence not as a retail offering, but rather Amazon’s internal answer to the growing complexity of the infrastructure that was responsible for powering Amazon.com and their e-commerce operations. Amazon quickly realized their cloud-based infrastructure was a compelling, cost-effective solution and opened it to the public in 2006.
At the time of writing this article, AWS is worth an estimated $250B (yes, that’s a B for BILLION) and used by thousands of companies and developers worldwide.
What You Will Build
I feel the best way to learn is by doing. I’ll walk you through building a small, Vue app with an Express REST server. You will secure your app using Okta’s OpenID Connect (OIDC) which enables user authentication and authorization with just a few lines of code.
You will begin by building the Vue frontend and deploy it to Amazon S3. Then you will leverage Amazon CloudFront to distribute your Vue frontend to edge servers all around the world. Lastly, you will create an Express API server and deploy it with Serverless. This API server will contain a method to fetch “secure data” (just some dummy data) which requires a valid access token from the client to retrieve.
The goal of this article is to show you how to leverage multiple AWS services rather than just spinning up a single EC2 instance to serve your app. With this services-based approach, you have a limitless scale, zero maintenance, and a cost-effective way to deploy apps in the cloud.
What is Okta?
Okta is a cloud service that allows developers to manage user authentication and connect them with one or multiple applications. The Okta API enables you to:
Authenticate and authorize your users
Store data about your users
Perform password-based and social login
Secure your application with multi-factor authentication
And much more! Check out our product documentation
Register for a free developer account, and when you’re done, come on back so we can learn more deploying a Vue app to AWS.
Bootstrap Frontend
You are going to build the Vue frontend to your secure app first and deploy it to Amazon S3 and Amazon CloudFront. Amazon S3 (Simple Storage Service) is a highly redundant, object-based file store that is both powerful and featureful. In the scope of this article, we will focus on one of the best features S3 provides: Static website hosting.
To get started quickly, you can use the scaffolding functionality from vue-cli to get your app up and running quickly. For this article, you can use the webpack template that includes hot reloading, CSS extraction, linting, and integrated build tools.
To install vue-cli run:
npm install -g [email protected]
Next up is to initialize your project. When you run the following vue init command, accept all the default values.
vue init webpack secure-app-client cd ./secure-app-client npm run dev
The init method should also install your app’s dependencies. If for some reason it doesn’t, you can install them via npm install. Finally, open your favorite browser and navigate to http://localhost:8080. You should see the frontend come alive!
About Single Page Applications
When you create an application with Vue, you are developing a Single Page Application (or “SPA”). SPAs have numerous advantages over traditional multi-page, server-rendered apps. It’s important to understand the difference between SPAs and multi-page web applications — especially when it comes to deploying.
A SPA app is often referred as a “static app” or “static website.” Static, in this context, means that your application compiles all its code to static assets (HTML, JS, and CSS). With these static assets, there is no specialized web server required to serve the application to your users.
Traditional web applications require a specialized web server to render every request to a client. For each of these requests, the entire payload of a page (including static assets) is transferred.
Conversely, within an SPA there is only an initial request for the static files, and then JavaScript dynamically rewrites the current page. As your users are navigating your app, requests to subsequent pages are resolved locally and don’t require an HTTP call to a server.
Vue-router and Creating Additional Routes
The component of an SPA that is required to rewrite the current page dynamically is commonly referred to as a “router”. The router programmatically calculates which parts of the page should mutate based off the path in the URL.
Vue has an official router that is aptly named vue-router. Since you used the vue-cli bootstrap, your app has this dependency and a router file defined (./src/router/index.js). Before we can define additional routes, we need to create the pages (or components) that you want the router to render. Create the following files in your project:
Homepage: ./src/components/home.vue
<template> <div> <h1>Home</h1> <div> <router-link to="/secure">Go to secure page</router-link> </div> </div> </template>
Secure Page (not secured… yet!) ./src/components/secure.vue
<template> <div> <h1>Secure Page</h1> <div> <router-link to="/">Go back</router-link> </div> </div> </template>
Using vue-router, you can inform the application to render each page based on the path.
Modify ./src/router/index.js to match the following code snippet:
import Vue from 'vue' import Router from 'vue-router' import Home from '@/components/home' import Secure from '@/components/secure' Vue.use(Router) let router = new Router({ routes: [ { path: '/', name: 'Home', component: Home }, { path: '/secure', name: 'Secure', component: Secure } ] }) export default router
Try it out! Tab back to your browser, and you should see the new home screen. If you click on the “Go to secure page” link you will notice the page (and URL) change, but no request was sent to a server!
Understand Hash History
As you navigated between the two pages above, you might have seen that the URL looks different than expected (do you noticed the “#/” at the beginning of the path?)
http://localhost:8080/#/ and http://localhost:8080/#/secure
The reason the URL looks like is because vue-router’s default mode is hash mode. Hash mode simulates a new URL change without instructing the browser to reload the page. This behavior is what allows SPA’s to navigate pages without forcing your browser to make any additional HTTP requests. Vue-router listens for changes in the hash portion of the URL (everything after the “#”) and responds accordingly based on the routes configured.
You can change the mode of vue-router to leverage history mode which will give your app “pretty URLs” like:
http://localhost:8080/secure
But, this comes with a significant drawback — especially when you are deploying. Since your SPA compiles to a static assets, there is just one single entry point index.html. If you try to access a page direction that is not index.html page (i.e.; http://localhost:8080/secure) the web server will return a 404 error. Why? The browser is sending a GET /secure request to the server and trying to resolve to the filesystem “/secure” (and the file doesn’t exist). It does work when you navigate to /secure from the homepage because vue-router prevents the default behavior of the browsers and instructs the router instance to fire in any mode.
By using history mode, you have to take additional steps to make sure page refreshes work correctly. You can read more about HTML5 History Mode. To keep things easy, I will show you a simple trick to ensure your refreshing works with AWS CloudFront.
Enable history mode by modifying ./router/index.js with the following setting.
let router = new Router({ mode: 'history', })
Note: The dev server (npm run dev) automatically rewrites the URL to index.html for you. So the behavior you see locally is how it should work in production.
Building Your Single Page Application
Now that you have a simple, two-page frontend working locally, it’s time to build your app and get it deployed to AWS!
Because you used vue-cli scaffolding, a single call to the included build script is all you need. From your project root, run npm run build and webpack will build your application into the target ./dist directory. If the dev server is still running in your console, you can press CTRL+C.
If you open the ./dist folder and you should see the results of the build process:
./index.html - This is the entry point of your SPA. It’s a minified HTML document with links to the apps CSS and JS.
./static - This folder contains all your compiled static assets (JS and CSS)
During the build, you might have noticed the following notification: Tip: built files are meant to be served over an HTTP server. Opening index.html over file:// won’t work. If you want to test your newly compiled application locally, you can use serve (install via npm install -g serve). Run serve ./dist and it will output a URL for you to load into your browser.
This also gives you to have a hands-on experience with the major caveat of history mode with vue-router. After running serve ./dist, click on the “Go to secure page”. You should see a 404 error.
Getting Started with AWS
You will need an AWS account to continue beyond this point. If you already have an AWS account, you can skip ahead. If you don’t, it’s a simple process that only takes a few minutes.
Navigate to the Amazon Web Services home page
Click Sign Up (or if you have signed into AWS recently choose Sign In to the Console)
If prompted, you can select “Personal” for account type
Complete the required information, add a payment method, and verify your phone number
After your account is created, you should receive a confirmation email
Log in!
Note: Amazon requires you to enter a payment method before you can create your account. All the services discussed in this article are covered under AWS Free Tier which gives you 12 months FREE.
Host Your App on Amazon S3
Since your SPA is comprised of only static assets, we can leverage Amazon S3 (Simple Storage Service) to store and serve your files.
To get started, you will need to create a bucket. Buckets are a logical unit of storage within S3, and you can have up to 100 buckets per AWS account by default (if you are studying for the AWS Certified Solutions Architect exam, you should know this!). Each bucket can have its own configuration and contain unlimited files and nested folders.
After you log in to your AWS Console, navigate to the S3 console (you can do this under AWS services search for “S3”).
Click “Create Bucket” and enter a Bucket name. Important: Bucket names are unique across the entire AWS platform. I chose bparise-secure-app-client for this article, but you might need to be creative with your naming!
Click “Create” in the bottom left.
You should now see your bucket listed. Next, let’s configure it for static website hosting.
Click your Bucket name and then choose the “Properties” tab.
Click on “Static website hosting” box
Choose “Use this bucket to host a website” and add “index.html” as the index document. Click “Save”.
At the top of the Static website hosting box, you should see a URL for “Endpoint”. This is the publicly accessible URL to view your static website. Open the link into a new browser window, and you should see this:
Access Denied and S3 Bucket Policies
Yes, you should see a 403 Forbidden error! By default, S3 bucket permissions are deny all. To access your bucket’s contents, you must explicitly define who can access your bucket. These bucket permissions are called a Bucket Policy.
To add a Bucket Policy, click on the “Permissions” tab and click “Bucket Policy” button at the top. The following policy allows anyone to read any file in your bucket. Make sure to replace “YOUR-BUCKET-NAME” with your actual bucket name.
{ "Version": "2012-10-17", "Statement": [ { "Sid": "PublicReadAccess", "Effect": "Allow", "Principal": "*", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::YOUR-BUCKET-NAME/*" } ] }
Bucket Policies can be quite complex and powerful. But, the main parts of the policy that you should be aware of are:
"Effect": "Allow"
"Principal": "*" - Who the policy covers (“*” implies everyone)
"Action": "s3:GetObject" - The action allowed (s3:GetObject allows read-only access to all objects in your bucket)
"Resource": "arn:aws:s3:::YOUR-BUCKET-NAME/*" - Which bucket and objects the policy is about.
Click “Save” on the Bucket Policy editor. You should notice a new error is displayed if you set up the policy correctly:
This warning is good advice and a rule of thumb for all S3 buckets. But, since our bucket is exclusively used to host a static website, we don’t have to worry about anyone accessing a file within the bucket they shouldn’t.
Tab back to your browser and refresh the endpoint. You should now see a 404 Not Found error. This error is much easier to resolve because you don’t have any files in your bucket yet.
Deploy to AWS with aws-cli
Now that you have a bucket created and permissions correctly set, it’s time to upload your static assets. Although you can do this manually through the interface by using the “Upload” button, I feel using the aws-cli is more efficient.
Installing asw-cli is different based on your OS. Choose one:
The post How to Deploy Your Secure Vue.js App to AWS appeared first on SitePoint.
by Brandon Parise via SitePoint https://ift.tt/2QpWWN7
0 notes