投稿時間:2022-01-09 09:11:41 RSSフィード2022-01-09 09:00 分まとめ(15件)

カテゴリー等 サイト名等 記事タイトル・トレンドワード等 リンクURL 頻出ワード・要約等/検索ボリューム 登録日
TECH Engadget Japanese 米国の一部ホンダ車でGPSナビの日付が2002年に戻る不具合。GPSロールオーバーが原因か https://japanese.engadget.com/older-honda-cars-stuck-in-the-year-2002-232026131.html 販売 2022-01-08 23:20:26
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) Swiftを知ってる人いますか? https://teratail.com/questions/377262?rss=all javascript 2022-01-09 08:56:17
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) getCookie.jsがうまく機能してないみたいです https://teratail.com/questions/377261?rss=all getCookiejsがうまく機能してないみたいです前提・実現したいことJavaScriptでCookieを設定して表示したいのですが、思ったように表示されない。 2022-01-09 08:16:25
AWS AWSタグが付けられた新着投稿 - Qiita AWS Batch でゲノムマッピングをしてみる https://qiita.com/quryu/items/4477a4cf417614fbe69f ジョブ定義の作成「EC」を選択し、ジョブの試行は「」を入力します。 2022-01-09 08:17:55
Docker dockerタグが付けられた新着投稿 - Qiita AWS Batch でゲノムマッピングをしてみる https://qiita.com/quryu/items/4477a4cf417614fbe69f ジョブ定義の作成「EC」を選択し、ジョブの試行は「」を入力します。 2022-01-09 08:17:55
Ruby Railsタグが付けられた新着投稿 - Qiita {自分用メモ}Githubにプッシュ&Herokuにデプロイまで https://qiita.com/Bjp8kHYYPFq8MrI/items/3be30fea7e184f730bef gitinitgitaddAgitcommitmInitializerepositoryここまではOK次に、と同じ手順でGitHubで新しいリポジトリを作成しますこのときリポジトリを図のようにprivateにしておくことをお忘れなく。 2022-01-09 08:16:02
技術ブログ Developers.IO SNSトピックサブスクライブ方法によるSQSキューアクセスポリシーの違い https://dev.classmethod.jp/articles/sns-sqs-subscribe-access-policy/ amazonsns 2022-01-08 23:05:28
海外TECH DEV Community How to Implement CORS and Authentication in NodeJS https://dev.to/olanetsoft/how-to-implement-cors-and-authentication-in-nodejs-214c How to Implement CORS and Authentication in NodeJSIn this tutorial we will learn how to authenticate users secure endpoints and Cross Origin Resource Sharing CORS in NodeJs PrerequisitesYou ll need the following to follow along with this tutorial A working grasp of JavaScript A good understanding of Node js A working knowledge of MongoDB or another database of your choice Postman and a basic understanding of how to utilize it What is authentication and authorizationSecurity uses authentication and authorization especially when gaining access to a system But there s a big difference between getting into a house authentication and what you can do once you re there authorization AuthenticationAuthentication is the process of confirming a user s identity by obtaining credentials and utilizing those credentials to validate the user s identity If the certificates are valid the authorization procedure begins You were already familiar with the authentication procedure because we all go through it daily whether at work logging onto your computer or at home passwords logging into a website However most things connected to the Internet require you to provide credentials to prove your identity AuthorizationThe process of granting authenticated users access to resources by verifying whether they have system access permissions is known as authorization In addition authorization allows you to restrict access privileges by granting or denying specific licenses to authenticated users After the system authenticates your identity authorization occurs providing you full access to resources such as information files databases finances locations and anything else On the other hand approval impacts your ability to access the system and the extent to which you can do so Cross Origin Resource Sharing CORS CORS is an HTTP header based system that allows a server to specify any other origins domain scheme or port from which a browser should enable resources to be loaded other than its own CORS also uses a system in which browsers send a preflight request to the server hosting the cross origin help to ensure that it will allow the actual request We will be using JSON web token standard for representing claims between two parties What is JWTJSON Web Tokens JWT are an open industry standard defined by RFC to represent claims between two parties You can use jwt io to decode verify and create JWT for example JWT defines a concise and self contained way for exchanging information between two parties as a JSON object This information may be reviewed and trusted because it is signed JWTs can be signed with a secret using the HMAC algorithm or a public private key pair from RSA or ECDSA We ll see some examples of how to use them in a bit Let s get started Node js development using a token for authenticationTo get started we ll need to set up our project Please navigate to a directory of your choice on your machine and open it in the terminal to launch Visual Studio Code Then execute code Note If you don t have Visual Studio Code installed on your computer code won t work A Create a directory and set it up npmCreate a directory and initialize npm by typing the following command Windows power shellmkdir cors auth projectcd cors auth projectnpm init yLinuxmkdir cors auth projectcd cors auth projectnpm init y B Create files and directoriesIn step A we initialized npm with the command npm init y which automatically created a package json We will create the model middleware config directory and their files for example user js auth js database js using the commands below mkdir model middleware configtouch config database js middleware auth js model user jsWe can now create the index js and app js files in the root directory of our project with the command touch app js index jsAs seen in the illustration below C Install dependenciesWe ll install several dependencies like mongoose jsonwebtoken express dotenv bcryptjs cors and development dependency like nodemon to restart the server as we make changes automatically Because I ll be utilizing MongoDB in this lesson we ll install mongoose and the user credentials will be checked against what we have in our database As a result the entire authentication process isn t limited to the database we ll use in this tutorial npm install cors mongoose express jsonwebtoken dotenv bcryptjs npm install nodemon D D Create a Node js server and connect your databaseNow add the following snippets to your app js index js database js and env files in that order to establish our Node js server and connect our database In our database js config database js const mongoose require mongoose const MONGO URI process env exports connect gt Connecting to the database mongoose connect MONGO URI useNewUrlParser true useUnifiedTopology true useCreateIndex true useFindAndModify false then gt console log Successfully connected to database catch error gt console log database connection failed exiting now console error error process exit In our app js auth cors project app jsrequire dotenv config require config database connect const express require express const app express app use express json Logic goes heremodule exports app In our index js auth cors project index jsconst http require http const app require app const server http createServer app const API PORT process env const port process env PORT API PORT server listening server listen port gt console log Server running on port port Our file as you can see requires various environment variables If you haven t already create a new env file and add your variables before running our application In our env API PORT MONGO URI Your database URIEdit the scripts object in our package json to look like the one below to start our server scripts start node index js dev nodemon index js test echo Error no test specified amp amp exit The above snippet was successfully inserted into theapp js index js and database js files So we started by creating our node js server in index js and then importing the app js file which already had routes configured Then as mentioned in database js we used mongoose to build a database connection npm run dev is the command to start our application Both the server and the database should be up and running without crashing E Create user model and routeAfter registering for the first time we ll establish our schema for the user details and when logging in we ll check them against the remembered credentials In the model folder add the following snippet to user js model user jsconst mongoose require mongoose const userSchema new mongoose Schema first name type String default null last name type String default null email type String unique true password type String module exports mongoose model user userSchema Let s create the routes for register and login respectively In app js in the root directory add the following snippet for the registration and login app js importing user contextconst User require model user Registerapp post register req res gt our register logic goes here Loginapp post login req res gt our login logic goes here F Implement register and login functionalityThese two routes will be implemented in our application Before storing the credentials in our database we ll use JWT to sign and bycrypt to encrypt We will Get user input from the register route Verify the user s input Check to see if the user has already been created Protect the user s password by encrypting it Make a user account in our database Finally construct a JWT token that is signed Modify the register route structure we created earlier as shown below app js app post register async req res gt Our register logic starts here try Get user input const firstName lastName email password req body Validate user input if email amp amp password amp amp firstName amp amp lastName res status send All input is required check if user already exist Validate if user exist in our database const oldUser await User findOne email if oldUser return res status send User Already Exist Please Login Encrypt user password encryptedUserPassword await bcrypt hash password Create user in our database const user await User create first name firstName last name lastName email email toLowerCase sanitize password encryptedUserPassword Create token const token jwt sign user id user id email process env TOKEN KEY expiresIn h save user token user token token return new user res status json user catch err console log err Our register logic ends here Note Update your env file with a TOKEN KEY which can be a random string Using Postman to test the endpoint we ll get the below response after a successful registration We will Get user input for the login route Verify the user s input Check to see if the user is genuine Compare the user password to the one we saved earlier in our database Finally construct a JWT token that is signed Make the login route structure that we defined earlier look like this app post login async req res gt Our login logic starts here try Get user input const email password req body Validate user input if email amp amp password res status send All input is required Validate if user exist in our database const user await User findOne email if user amp amp await bcrypt compare password user password Create token const token jwt sign user id user id email process env TOKEN KEY expiresIn h save user token user token token user return res status json user return res status send Invalid Credentials Our login logic ends here Using Postman to test we ll get the response shown below after a successful login G Create middleware for authenticationA user can be created and logged in successfully Despite this we ll establish a route that requires a user token in the header which will be the JWT token we created before Add the following snippet inside auth js middleware auth jsconst jwt require jsonwebtoken const config process env const verifyToken req res next gt const token req body token req query token req headers x access token if token return res status send A token is required for authentication try const decoded jwt verify token config TOKEN KEY req user decoded catch err return res status send Invalid Token return next module exports verifyToken Create the welcome route and edit app js with the following code to test the middleware app jsconst auth require middleware auth app post welcome auth req res gt res status send Welcome to FreeCodeCamp When we try to access the welcome route we just built without sending a token in the header with the x access token key we get the following response We can now re test by adding a token in the header with the key x access token The response is seen in the image below Implementing Cross Origin Resource Sharing CORS CORS is a node js package that provides a Connect Express middleware that can be used to enable CORS with a variety of parameters Easy to Use Enable All CORS Requests Adding the following snippet to app js allows us to add cors to our application and enable all CORS requests const cors require cors Newly addedconst app express app use cors Newly addedapp use express json limit mb Enable CORS for a Single RouteUsing the welcome route as an example We may activate CORS for a single route in our application by adding the following snippet in app js app get welcome cors auth req res gt res status send Welcome to FreeCodeCamp Configuring CORSAs shown below we can set options in the cors package by adding parameters to configure it const corsOptions origin optionsSuccessStatus for some legacy browsers app get welcome cors corsOptions auth req res gt res status send Welcome to FreeCodeCamp Kindly check out NPM CORS PACKAGE to read more about Cross Origin Resource Sharing You can click here to check the complete code on GitHub ConclusionIn this article we learned about JWT authentication authorization and CORS and how to create an API in Node js that uses a JWT token for authentication Thank you I d love to connect with you at Twitter LinkedIn GitHub PortfolioSee you in my next blog article Take care 2022-01-08 23:26:12
海外TECH DEV Community Simple server on Gorilla WebSocket https://dev.to/davidnadejdin/simple-server-on-gorilla-websocket-52h7 Simple server on Gorilla WebSocketIn this small tutorial we ll take a closer look at using Gorilla WebSocket to write our own websocket server at a more functional level than the basic example and easier to understand than the chat example What will our server be able to do Send new messages from clients in a callbackKeep active connections and close delete inactiveSend messages to active connectionsFirst we use the standard http help server net http so that we can catch connection requests package mainimport fmt html net http func main http HandleFunc echo http ListenAndServe nil func echo w http ResponseWriter r http Request fmt Fprintf w Hello q html EscapeString r URL Path Now let s teach it to upgrade the connection import github com gorilla websocket net http var upgrader websocket Upgrader CheckOrigin func r http Request bool return true Accepting all requests func echo w http ResponseWriter r http Request connection upgrader Upgrade w r nil connection Close Close connection We now have a client connection which we close immediately We can loop through the messages that the client sends to us and send them back func echo w http ResponseWriter r http Request connection upgrader Upgrade w r nil for message connection ReadMessage connection WriteMessage websocket TextMessage message go messageHandler message func messageHandler message byte fmt Println string message Let s teach our server to close the connection func echo w http ResponseWriter r http Request connection upgrader Upgrade w r nil for mt message err connection ReadMessage if err nil mt websocket CloseMessage break Exit the loop if the client tries to close the connection or the connection with the interrupted client connection WriteMessage websocket TextMessage message go messageHandler message connection Close To be able to send messages over different connections we need to store them somewhere in our case the simplest map is suitable var clients map websocket Conn boolfunc echo w http ResponseWriter r http Request connection upgrader Upgrade w r nil clients connection true Save the connection using it as a key for mt message err connection ReadMessage if err nil mt websocket CloseMessage break Exit the loop if the client tries to close the connection or the connection with the interrupted client Send messages to all clients go writeMessage message go messageHandler message delete clients connection Removing the connection connection Close func writeMessage message byte for conn range clients conn WriteMessage websocket TextMessage message Now we can pack our server into a structure to be able to send and receive messages from outside package wsimport github com gorilla websocket net http var upgrader websocket Upgrader CheckOrigin func r http Request bool return true Accepting all requests type Server struct clients map websocket Conn bool handleMessage func message byte New message handler func StartServer handleMessage func message byte Server server Server make map websocket Conn bool handleMessage http HandleFunc server echo go http ListenAndServe nil return amp server func server Server echo w http ResponseWriter r http Request connection upgrader Upgrade w r nil server clients connection true Save the connection using it as a key for mt message err connection ReadMessage if err nil mt websocket CloseMessage break Exit the loop if the client tries to close the connection or the connection is interrupted go server handleMessage message delete server clients connection Removing the connection connection Close func server Server WriteMessage message byte for conn range server clients conn WriteMessage websocket TextMessage message package mainimport fmt simple webcoket ws func main server ws StartServer messageHandler for server WriteMessage byte Hello func messageHandler message byte fmt Println string message Now we have an implementation of a simple webscoket server that is capable of receiving and sending messages over active connections 2022-01-08 23:22:12
海外TECH DEV Community React.js : debouncing and throttling https://dev.to/ridhamz/reactjs-debouncing-and-throttling-ccm React js debouncing and throttling IntroductionIn order to build a professional web application optimization and performance are two important things you need to care about There are many tips and techniques used to increase the performance of a web application such as Debouncing and Throttling When it comes to debouncing and throttling developers often confuse During this blog I will go throw these two techniques in details using react js but it is the same principle for vanilla JavaScript or any other JavaScript framework DebouncingBefore dive deep into debouncing let s see a simple and normal example that implement a search box that allows users to search something without clicking any button function App const handleChange e gt console log api call return lt div className App gt lt header className App header gt lt p gt Search lt p gt lt input type text onChange handleChange gt lt header gt lt div gt The issue is that handleChange is very expensive and this is bad to the server because it will receive many HTTP requests in the same time To solve the problem we need to use a debounce function Definition and implementation of a debounce functionA debounce function is called after a specific amount of time passes since its last call function debounce fn delay let timer return function args clearTimeout timer timer setTimeout gt fn args delay The idea is to define a high order function called debounce takes as arguments a callback function and a delay in ms then returns a new function that sets the timer to execute the callback after the timer done The secret here is that every call of the function returned from the debounce function will cancel the previous timer using cleartimeout timer and start a new timer With this approach we can be sure that the callback function will be executed just once after the time that we passed as an argument in the last call Implement debounce function into our example lt div className App gt lt header className App header gt lt p gt Search lt p gt lt input type text onChange debounce handleChange gt lt header gt lt div gt Result ThrottlingLet s assume that we have an event listener in our app to track the movement of the user mouse then send data to a backend server to do some operations based on the location of the mouse const handleMouseMove e gt every time the mouse moved this function will be invoked console log api call to do some operations event listener to track the movement of the mouse window addEventListener mousemove handleMouseMove If we stick with this solution we will end up with a down backend server because it will receive a hundred of requests in short duration API calls in few seconds is very very bad To fix this issue we need to limit the number of API calls and this kind of problem can be solved using a throttle function Definition and implementation of a throttle functionA throttle function is a mechanism to limit the number of calls of another function in a specific interval any additional calls within the specified time interval will be ignored function throttle fn delay let run false return function args if run fn args run true setTimeout gt run false delay The throttle function accepts two arguments fn which is a function to throttle and delay in ms of the throttling interval and returns a throttled function Implement throttle function into our exampleconst handleMouseMove e gt every time the mouse moved this function will be invoked console log api call to do some operations event listener to track the movement of the mouse window addEventListener mousemove throttle handleMouseMove ms gt second Result ConclusionDebouncing and Throttling are two amazing things they can increase the performance of your web application to another level The difference between them is Debouncing execute function after specific amount of time and every call cancel the previous timer and start new timer Throttling execute a function only once in a given period of time Choosing one of them depends on the case 2022-01-08 23:04:44
ニュース BBC News - Home Novak Djokovic: Having Covid gave tennis star vaccine exemption - lawyers https://www.bbc.co.uk/news/world-australia-59920379?at_medium=RSS&at_campaign=KARANGA australia 2022-01-08 23:50:28
ニュース BBC News - Home Covid: Thousands protest in France against proposed new vaccine pass https://www.bbc.co.uk/news/world-europe-59925408?at_medium=RSS&at_campaign=KARANGA areas 2022-01-08 23:08:40
ニュース BBC News - Home The Papers: 'End of free lateral flow tests' and 'stop mass jabs' https://www.bbc.co.uk/news/blogs-the-papers-59925428?at_medium=RSS&at_campaign=KARANGA covid 2022-01-08 23:21:36
北海道 北海道新聞 奥川3戦連発、6点目 サッカー、ドイツ1部 https://www.hokkaido-np.co.jp/article/631475/ 連発 2022-01-09 08:04:00
ニュース THE BRIDGE Duolingoに学ぶ〝Employee Experience〟のベストプラクティス(2/3) https://thebridge.jp/2022/01/duolingo-employee-experience-2 Duolingoに学ぶ〝EmployeeExperience〟のベストプラクティス本稿は独立系ベンチャーキャピタル、ジェネシア・ベンチャーズのインベストメントマネージャー水谷航己氏によるもの。 2022-01-08 23:15:20

コメント

このブログの人気の投稿

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

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

投稿時間:2020-12-01 09:41:49 RSSフィード2020-12-01 09:00 分まとめ(69件)