投稿時間:2022-07-24 21:08:04 RSSフィード2022-07-24 21:00 分まとめ(12件)

カテゴリー等 サイト名等 記事タイトル・トレンドワード等 リンクURL 頻出ワード・要約等/検索ボリューム 登録日
海外TECH DEV Community Let's build and deploy a full stack MERN web application https://dev.to/itsrakesh/lets-build-and-deploy-a-full-stack-mern-web-application-1p5 Let x s build and deploy a full stack MERN web applicationI am sure that when you first begin learning full stack web development using the MERN stack you will have questions like What is it like to build a full stack application What exactly are frontend and backend How do we connect them Is there any magic etc So I m writing this tutorial to address your queries and show you how to build a full stack web application NoteThe goal of this tutorial is to provide you with a high level overview of what it s like to build a full stack application rather than a detailed explanation of MERN stack technologies Let s get started PrerequisitesBasic understanding of MERN stack technologies NodeJs installedMongoDB account The ProjectTo keep things simple while covering more concepts we will create a simple mini project We will create a simple productivity tracker application in which you can record what activities you accomplished during the day and for how much time So that we may see how we are spending our time We can also see all of the stuff on the home page Source code How does this work You enter an activity and the amount of time you spent on it The data is then submitted to the NodeJs backend That information will be stored in the MongoDB database All activities are displayed on the homepage We know what we need to do now let s figure out how to do it Frontend Client What is a Frontend Client application Client application refers to the frontend part of a full stack application The client sends requests to the server and receives responses That request could be the client sending information to the server or asking for information The client is the visible part of a full stack application Let s start by making a client Make a new folder and label it productivity app Create a react app called client using create react app npx create react app clientStart your coding editor IDE and open the project This is how your folder structure will look ├ーREADME md├ーpackage lock json├ーpackage json├ーpublic│├ーfavicon ico│├ーindex html│├ーlogo png│├ーlogo png│├ーmanifest json│└ーrobots txt└ーsrc ├ーApp css ├ーApp js ├ーApp test js ├ーindex css ├ーindex js ├ーlogo svg ├ーreportWebVitals js └ーsetupTests jsFor the time being we are only interested in the App js and App css files Remove all existing code from the App js and App css files Let s make a react component Add the App component to the App js file import App css const App gt return lt div gt My App lt div gt export default App The above code creates and renders the App component Run the following command in the terminal and navigate to http localhost npm startDesign the app We want the user to enter the name of the activity as well as the time it took Then we ll display all of the activities on the homepage Copy and paste this HTML code into the App component lt div className app gt lt header className app header gt lt h gt Productivity Tracker lt h gt lt form gt lt div gt lt label htmlFor activity gt Activity lt label gt lt input type text id activity name activity autoComplete off gt lt div gt lt div gt lt label htmlFor time gt Time Taken lt label gt lt input type text id time name time autoComplete off gt lt div gt lt button type submit gt Add lt button gt lt form gt lt header gt lt main className app main gt lt h gt Today lt h gt lt ol gt lt li gt Activity hours lt li gt lt li gt Activity min lt li gt lt li gt Activity hours and min lt li gt lt ol gt lt main gt lt div gt Our app will now look like this Let us now add some CSS Copy and paste the CSS code from this file into the App css file Our app now appears as follows Add logic The activities are currently hardcoded So let s save and use activities in a state const activities setActivities useState lt main className app main gt lt h gt Today lt h gt activities amp amp activities length gt lt ol gt activities map activity gt lt li key activity id gt activity name activity time lt li gt lt ol gt lt p gt No activities yet lt p gt lt main gt But Where do we get our activities How do we add an activity to the list A backend is required to handle all of this Backend ServerThe backend component of a full stack application is frequently referred to as the Server A server s job is to continuously listen to requests implement some business logic and return the results DatabaseLet s create a database first before we create a server To record and add our activities we need a database We can use a cloud database instead of hosting a database MongoDB offers a free cloud database atlas that may be used for small hobby projects Log in to your MongoDB account Create a project Then go to Browse collections and create a database For the collection name write activities Click on Overview and then in the overview tab click on CONNECT gt Connect your application Copy the connection string Your connection string should look like this mongodb srv lt username gt lt password gt lt clusterUrl gt lt databaseName gt retryWrites true amp w majoritySave this string somewhere safe ServerWe now have a database Let us now build our application logic and connect it to the database Make a folder called Server in your project folder In the terminal open the folder and type npm init Fill in all the details Install the following packages npm i express mongoose dotenvexpress Used to create a server mongoose Used to work with MongoDB databasedotenv Used to load environment variables Make a env file and save your connection string in a variable called MONGODB URI MONGODB URI yourconnectionstringCreate a server js file and paste this code const express require express const mongoose require mongoose const app express Loading the environment variables from the env file require dotenv config const PORT process env PORT const MONGODB URI process env MONGODB URI mongodb localhost todoapiDB Telling the application to use the express json middleware This middleware will parse the body ofany request that has a Content Type of application json app use express json This is a route handler It is listening for a GET request to the root route of the application When it receives a request it will send back a response with the string Hello World app get req res gt res send Hello World Connecting to the database and then starting the server mongoose connect MONGODB URI useNewUrlParser true then gt app listen PORT console log Server stated on port catch err gt console log err Run the below command and go to http localhost in your browser You will see something like this Make sure you have nodemon installed globally npm run devThis means the server is running successfully Create a schema model to store activity Create a folder called models and in that folder create a file activity model js Copy and paste the below code const mongoose require mongoose const Schema mongoose Schema Creating a new schema for the activity model const activitySchema new Schema name type String required true time type String required true module exports mongoose model Activity activitySchema Implement application logic in controllers Create a folder called controllers and in that folder create a file activity controller js We need to implement two things Get all activities to show on the homepage and Add an activity const Activity require models activity model It s an async function that uses the Activity model to find all activities and then returns a status of with the activities in the response body const getActivities async req res gt try const activities await Activity find res status json activities catch err res status json message err message It creates a new activity and saves it to the database const addActivity async req res gt const activity new Activity req body try const newActivity await activity save res status json newActivity catch err res status json message err message module exports getActivities addActivity Register routes to handle requests Create a folder called routes and in that folder create a file activity route js Copy and paste the below code const express require express const getActivities addActivity require controllers activity controller const router express Router Creating a route for the get request router get activities getActivities Creating a route for the post request router post activity addActivity module exports router Final folder structure will be like this ├ーcontrollers│└ーactivity controller js├ーmodels│└ーactivity model js├ーroutes│└ーactivity route js├ーpackage lock json├ーpackage json└ーserver jsUse the above routes in the app Open the server js file and use the registered routes const ActivityRouter require routes activity route Telling the application to use the ActivityRouter for any requests that start with api app use api ActivityRouter Our backend is now wholly operational we can add and retrieve data Let s look at how to connect the backend to the front end Connecting client and serverIt is not difficult to connect the client and server It s as simple as adding a URL Navigate to the client folder and create a env localfile Paste the backend URL into a variable REACT APP BACKEND URL http localhost apiNavigate to the client folder and open App js When the user clicks the Add button we must make a POST request to the server via the api activity route Create a function called handleSubmit and add the onSubmit attribute to the form element In this function we must send a request to the server passing the activity name and time through the body const addActivity async event gt event preventDefault const newActivity name event target activity value time event target time value await fetch process env REACT APP BACKEND URL activity method POST headers Content Type application json body JSON stringify newActivity event target activity value sets input empty after clicking submitevent target time value sets input empty after clicking submitwindow location reload reloads the window after sending request lt form onSubmit addActivity gt Enter an activity name and time then submit Ensure that the server is also up and running An error message will appear in the browser console Access to the server is banned by CORS Cross Origin Resource Sharing policy which means your server does not allow access to its resources We may avoid this problem by using the cors npm package Open the server folder and install the cors package npm i corsThen use this package in server js const cors require cors Allowing the frontend to access the backend app use cors Restart the server Try to add activity It will work this time You can see the data that has been added to the database Now we must display the list of newly added activities We must display activities as soon as the component renders We can accomplish this by using useEffect hook Fetch the data from the server and save it to the state Fetching the data from the backend and setting the state of activities to the data useEffect gt const fetchData async gt const result await fetch process env REACT APP BACKEND URL activities const data await result json setActivities data fetchData Now you can see all the activities on the homepage Hosting full stack applicationBefore hosting we must keep secrets safe and avoid committing unnecessary files folders Open the server folder Initialize git create a gitignore file and paste the following stuff node modules env BackendHeroku will be used for the backend Create a GitHub repository for the server application and push server code to it Access Heroku Select New gt Create new app Give your app a name choose a region and then click Create app Navigate to Settings gt Config Vars gt Reveal Config Vars gt Add Environment Variables Here Go to Overview and select GitHub as the deployment mechanism If you haven t already sign up for GitHub Select your repository Select Enable Automatic Deploys if you wish to create a deployment every time you commit to the repository Finally click Deploy Branch Make a note of the URL of the deployed site FrontendNetlify will host our client frontend part Create a GitHub repository for the client application and push client code to it Sign in to Netlify Select Add Site Select  GitHub Give GitHub permission Select your repository In Basic build settings For base directory Leave empty For build command npm run buildFor publish directory build Select Show advanced gt New variable In the key field enter the REACT APP BACKEND URL and the previously copied backend URL in the value field Select Deploy site That s all Open the URL in your browser and have fun Add your own features and share the URL in the comments Also read The flow of building a full stack web applicationDifferent ways to connect react frontend and node backendI hope this has given you an idea of how to develop a full stack MERN application Follow me for more Don t forget to subscribe to my Newsletter Thank you 2022-07-24 11:55:00
海外TECH DEV Community How JavaScript Works https://dev.to/iarchitsharma/how-javascript-works-5ec9 How JavaScript WorksIn this article we are going to take a look at the computer science behind Javascript NOTE Keep in mind that you do not need to understand these concepts to begin using JavaScript productively Years of development experience may be required before they truly sink in We learnt in the last article that Javascript is a programming language based on the ECMA Spec but to study how it works in a computer system we must travel to the absolute bottom of the stack which is the bare metal CPU and Memory on a machine When you run a JavaScript programme whether it s a web application in the browser or something server side with nodejs it needs to allocate memory on your RAM to store things for the runtime and variables and objects that you reference in your code and it also needs a thread from your CPU to actually execute the instructions in your code but here s the thing as a JavaScript developer you never really have to think about this stuff because it s a high level language High Level refers to the abstraction the language provides over the machine s bare metal hardware JavaScript is considered high level because it does not require direct interaction with the operating system hardware In addition it does not require memory management like C C because the runtime always uses garbage collection But what exactly do we mean by high level We re referring to the degree of abstraction or simplification that the language provides over the computer s hardware Machine code is the lowest level language it is a numeric language that can be executed directly by the CPU however it would be extremely difficult to build a website with it because you would have to memorize a number for each and every instruction that you want to run Moving up one level to Assembly provides some syntactic sugar but each assembly language is specific to a specific CPU or operating systemSo we can move up another level to the C language which provides a modern syntax and the ability to write cross platform programmes but developers must still be concerned with low level issues such as memory allocation Another step up brings us to languages like JavaScript and Python which use abstractions like garbage collectors and dynamic typing to simplify the way developers write their applications There are two basic techniques to convert programming language code into something that the CPU can actually execute so let s go ahead and define a few crucial terminology related to JavaScript One of them is called an Interpreter and the other is called a Compiler Interpreted or Just in Time Compiled Interpreted means the source code is converted to bytecode and executed at runtime as opposed to being compiled to a machine code binary at build time This is also why JS is commonly called a “scripting language Originally it was only interpreted but modern JS engines like V Spidermonkey and Nitro use various techniques to perform Just in Time Compilation or JIT for better performance Developers still use JS like an interpreted language while the engine magically compiles parts of source code to low level machine code behind the scenes JavaScript is an interpreted language which means that it requires an environment to read the actual source code and be executed We can show this by simply opening the browser and running some JavaScript code from the console This is different from compiled languages like Java or C which will statically analyse all of your code beforehand and then compile it into a binary that you can actually run on the computer JavaScript is a dynamically typed language which tends to be a common characteristic with high level interpreted languages We can examine this by comparing some statically typed Java code to some dynamically typed JavaScript code Dynamic Weakly Typed Dynamic most often refers to the type system JS is dynamic weakly typed language meaning you do not annotate variables with types string int etc and the true types are not known until runtime When comparing you ll notice that the Java code annotates things like integers and strings but the JavaScript types are unknown or implicit This is because the type is associated with a runtime value rather than the actual variables or functions in your code You may also hear that JavaScript is a Multi Paradigm language at this point Most general purpose programming languages support multiple paradigms allowing you to combine declarative functional techniques and imperative object oriented approaches Multi Paradigm means the language is general purpose or flexible JS can be used for declarative functional or imperative object oriented programming styles Prototypal inheritance is the foundation of JavaScript Everything in JavaScript is considered to be an object and each object in the language has a link to its prototype forming a prototype chain from which subsequent objects can inherit their behaviours If you re used to class based inheritance this could seem strange to you but it s one of the low level ideas that makes JavaScript a very flexible multi paradigm language Prototypal Inheritance means that objects can inherit behaviors from other objects This differs from classical inheritance where you define a class or blueprint for each object and instantiate it We will take a deep dive into prototypal inheritance later in this course Here is an Example let animal eats true let rabbit jumps true rabbit proto animal we can find both properties in rabbit now alert rabbit eats true alert rabbit jumps trueJavascript is a High level Interpreted Dynamically Typed Multi Paradigm Prototype Language but it is also a Single Threaded Garbage Collected Non Blocking language with an Event Loop that can be compiled Just In Time The first set of definitions is largely relevant to how javascript is laid out in ECMA however it doesn t describe how memory should be managed and it doesn t even mention the event loop in the entire page document so it s up to browser vendors to handle these implementation details Spider monkey from Mozilla and v from Google are two of the most popular implementations Their methods differ slightly but they both use a technique known as Just In Time Compilation In the case of v it will compile all of your JavaScript down to native machine code before running it rather than interpreting bytecode line by line as a normal interpreter would So while these JavaScript engines do not fundamentally change the way developers write code the JIT compiler improves performance in browsers and on Node Because JavaScript is a single threaded language it can only do one computation at a time Try this Open the console with Ctrl Shift J in this browser tab and then build a while loop that never stops while true If you try to click on something in this browser tab it will never catch the event since the single thread is locked in that while loop and can t move on to the next event Enter Chrome Task Manager and you should see the browser tab using nearly  of the CPU cores resources Go ahead and end the process and refresh the tab When you run your JavaScript code the machine allocates two regions of memory the call Stack and the Heap The call Stack is intended to be a high performance continuous memory region used to execute your functions When you call a function it generates a frame and a call stack with a copy of its local variables When you call a function within a function it adds another frame to the stack but when you return from a function it removes that frame from the stack I believe that going through some of your own code frame by frame is the best approach to grasp the call stack Here is a video for that When we encounter something a little more complex such as an object that may be referenced by several function calls outside of this local context the Heap comes into play The Heap is Garbage Collected which means that V or the JS runtime will try to clear up free memory when it s no longer referenced in your code This doesn t mean you shouldn t be concerned about memory but it does mean you don t need to manually allocate and free up memory as you would in C We ve already seen how a simple while loop can completely break a single threaded language so how can we handle any kind of long running task The answer is the Event Loop Event Loop Concurrency Model Event Loop refers to a feature implemented by engines like V that allow JS to offload tasks to separate threads Browser and Node APIs execute long running tasks separately from the the main JS thread then enqueue a callback function which you define to run on the main thread when the task is complete This is why JS is called non blocking because it should only ever wait for synchronous code from your JS functions Think of the Event Loop as message queue between the single JS thread and the OS Let s start from scratch and write our own code In its most basic form it s just a while loop that waits for messages from a queue and then processes their synchronous instructions until completion while queue waitForMessage queue processNextMessage In the browser you re already doing this without even thinking about it you might set up an Event Listener for a button click and when the user clicks it it sends a message to the queue and the runtime will process whatever JavaScript you defined as the callback for that event this is what makes JavaScript Non Blocking Because the only thing it ever does is listen to events and handle callbacks it s never actually waiting for a function s return value instead it s waiting for the CPU to process your synchronous code which is usually on a scale of microseconds Consider the first iteration of the event loop It will first handle all of the synchronous code in the script and then it will check if there are any messages or callbacks in the queue ready to be processed We can easily demonstrate this behaviour by adding a set timeout to the top of the script for seconds Here is an example that demonstrates this concept setTimeout does not run immediately after its timer expires const seconds new Date getSeconds setTimeout function prints out meaning that the callback is not called immediately after milliseconds console log Ran after new Date getSeconds seconds seconds while true if new Date getSeconds seconds gt console log Good looped for seconds break Now you might think that this timeout should be executed first because it is at the start of the file and has a timeout of seconds but the event loop won t get to it until the first iteration of synchronous code is completed What makes this unique is that you can offload long running jobs to completely separate thread pools in the browser For example you might make an HTTP call that takes a few seconds to resolve or interact with the file system on Node JS but you can do so without blocking the main JavaScript thread With the introduction of Promises and the Micro Task Queue JavaScript had to go and make things a little more strange If we include a Promise resolve after the setTimeout in our script setTimeout gt console log Do this first Promise resolve then n gt console log Do this Second You d think we have two asynchronous operations with zero delay here so the set timeout would fire first and the promise second but there s something called the Micro Task Queue for Promises which has priority over the main task queue used for Dom APIs and set timeouts etc This means that the handler for the Promise will be called back first In this case as the Event Loop iterates it will first handle the synchronous code then it will go to the Micro Task Queue and handle any callbacks that are ready from your promises It will finish by running the callbacks that are ready from your set timeouts or Dom APIs So this is how JavaScript works If all of this seems overwhelming don t worry because you don t need to know any of it to start building things with JavaScript Thank you for reading this article do follow me for more 2022-07-24 11:29:40
海外科学 NYT > Science ‘Parentese’ Is Truly a Lingua Franca, Global Study Finds https://www.nytimes.com/2022/07/24/science/parentese-babies-global-language.html similar 2022-07-24 11:11:06
ニュース BBC News - Home Kate Moss: I can tell a wrong 'un a mile away https://www.bbc.co.uk/news/uk-62271532?at_medium=RSS&at_campaign=KARANGA photoshoot 2022-07-24 11:46:26
ニュース BBC News - Home Ukraine war: Russian Foreign Minister Sergei Lavrov seeks Arab world's support https://www.bbc.co.uk/news/world-middle-east-62284377?at_medium=RSS&at_campaign=KARANGA ukraine 2022-07-24 11:27:18
ニュース BBC News - Home Girls Aloud race for Sarah Harding in Hyde Park https://www.bbc.co.uk/news/uk-england-london-62283989?at_medium=RSS&at_campaign=KARANGA harding 2022-07-24 11:25:16
北海道 北海道新聞 鹿児島・桜島で噴火 https://www.hokkaido-np.co.jp/article/709613/ 鹿児島県 2022-07-24 20:39:00
北海道 北海道新聞 江ノ電、ドア開いたまま列車走行 重大インシデントに認定 https://www.hokkaido-np.co.jp/article/709612/ 江ノ島電鉄 2022-07-24 20:26:00
北海道 北海道新聞 日本ハム 新庄監督は29日に復帰 https://www.hokkaido-np.co.jp/article/709608/ 新庄剛志 2022-07-24 20:04:00
北海道 北海道新聞 中国、実験施設の打ち上げ成功 宇宙ステーション連結へ https://www.hokkaido-np.co.jp/article/709607/ 宇宙ステーション 2022-07-24 20:03:00
北海道 北海道新聞 日本ハム稲葉GMらが陽性 楽天の2軍は4選手 https://www.hokkaido-np.co.jp/article/709606/ 日本ハム 2022-07-24 20:01:00
北海道 北海道新聞 南がイタリア1部ローマに移籍 サッカー女子日本代表DF https://www.hokkaido-np.co.jp/article/709605/ 日本代表 2022-07-24 20:01:00

コメント

このブログの人気の投稿

投稿時間:2021-06-17 22:08:45 RSSフィード2021-06-17 22:00 分まとめ(2089件)

投稿時間:2021-06-20 02:06:12 RSSフィード2021-06-20 02:00 分まとめ(3871件)

投稿時間:2021-06-17 05:05:34 RSSフィード2021-06-17 05:00 分まとめ(1274件)