TECH |
Engadget Japanese |
最大60%オフのKindle本 年末年始セールが開催中! 3万タイトル以上が対象。来年1月6日まで |
https://japanese.engadget.com/kindle-sale-082544447.html
|
amazon |
2021-12-21 08:25:44 |
TECH |
Engadget Japanese |
アップル本社屋内を映した動画が公開。「地球上で最も秘密の場所の1つ」にカメラが入る |
https://japanese.engadget.com/apple-park-most-secret-place-080034096.html
|
秘密 |
2021-12-21 08:00:34 |
ROBOT |
ロボスタ |
透明フィルムを貼るだけで5G通信の環境を改善 積水化学「5G通信向け透明フレキシブル電波反射フィルム」発表 |
https://robotstart.info/2021/12/21/sekisui-meta-5g-film.html
|
metamate |
2021-12-21 08:31:51 |
ROBOT |
ロボスタ |
医療IoT機器とファミリーロボット「BOCCO emo」が連動 ユカイ工学「CES 2022」に出展 未発表の新体感プロダクトも初公開へ |
https://robotstart.info/2021/12/21/yukai-engineering-ces-2022.html
|
boccoemo |
2021-12-21 08:12:38 |
IT |
ITmedia 総合記事一覧 |
[ITmedia News] 「超すごいIPv6本」電子版を無償配布 JPRSやNTTコムなども協賛 |
https://www.itmedia.co.jp/news/articles/2112/21/news133.html
|
itmedia |
2021-12-21 17:34:00 |
IT |
ITmedia 総合記事一覧 |
[ITmedia News] 「ミジュマル」が三重県の応援ポケモンに |
https://www.itmedia.co.jp/news/articles/2112/21/news132.html
|
地域活性化 |
2021-12-21 17:26:00 |
IT |
ITmedia 総合記事一覧 |
[ITmedia PC USER] Zoom、会議のスケジュール設定時にフォーカスモードを選択可能に |
https://www.itmedia.co.jp/pcuser/articles/2112/21/news126.html
|
itmediapcuserzoom |
2021-12-21 17:15:00 |
IT |
情報システムリーダーのためのIT情報専門サイト IT Leaders |
ネットワールド、バージョン管理システム「GitLab Enterprise」を販売開始 | IT Leaders |
https://it.impress.co.jp/articles/-/22494
|
ネットワールド、バージョン管理システム「GitLabEnterprise」を販売開始ITLeadersネットワールドは年月日、バージョン管理システム「GitLabEnterprise」米GitLab製を販売開始した。 |
2021-12-21 17:37:00 |
AWS |
AWS Japan Blog |
Petco と AWS がペットオーナーにもたらす利便性とパーソナライゼーション |
https://aws.amazon.com/jp/blogs/news/aws-is-how-petco-brings-greater-convenience-and-personalization-to-pet-parents/
|
Petcoは、ペットオーナーのペットケアを支援することを約束し、ペットの健康を維持するための高品質な製品とサービスを提供しています。 |
2021-12-21 08:10:39 |
python |
Pythonタグが付けられた新着投稿 - Qiita |
【Django】今まで出てきたエラー集(エラー内容・発生タイミング・原因・解決方法・参考サイトを記載) |
https://qiita.com/Yoshida-Programmer/items/00d56171fd419292a3f3
|
【Django】今まで出てきたエラー集エラー内容・発生タイミング・原因・解決方法・参考サイトを記載エラーリスト※随時更新していきます①djangotemplatelibraryInvalidTemplateLibraryInvalidtemplatelibraryspecifiedImportErrorraisedwhentryingtoloadrestframeworktemplatetagsrestframeworkNomodulenamedpytz発生タイミングpythonmanagepymakemigrations実行時に発生。 |
2021-12-21 17:41:36 |
python |
Pythonタグが付けられた新着投稿 - Qiita |
[py2rb] re.finditer 2 |
https://qiita.com/superrino130/items/09f89dbb90b2056b7541
|
pyrbrefinditerはじめに移植やってますrefinditerPythonimportrerulerKRPltWKPltMRPsequenceMRGETGVSIKNPRPSRPFSCFWRKGDVENIRKSDIGNEKKIDAKFNRLQYNLYYKPLSHHKAGLLYKELFFRSCFSYTTCSLDFQGKRHQVERKAVDIVLprintxendforxinrefinditerrulesequenceどうするRubyNGrbruleKRPltWKPltMRPsequenceMRGETGVSIKNPRPSRPFSCFWRKGDVENIRKSDIGNEKKIDAKFNRLQYNLYYKPLSHHKAGLLYKELFFRSCFSYTTCSLDFQGKRHQVERKAVDIVLpsequencescanruleflattencompactmapsequenceindexsizescanは正規表現ですが、indexは単純な検索なんですね。 |
2021-12-21 17:25:40 |
python |
Pythonタグが付けられた新着投稿 - Qiita |
RecBole を使ってレコメンドモデルの挙動の違いを観察する |
https://qiita.com/fufufukakaka/items/77878c1e23338345d4fa
|
チューニングをしていないのでこの結果は決定版ではないのですが、一応同じ条件で比較したにしては全然違う結果になったことが皆さんにも伝わったのではないかと思います。 |
2021-12-21 17:13:37 |
js |
JavaScriptタグが付けられた新着投稿 - Qiita |
OutSystemsでの帳票出力を考える(後編)Stimulsoft EX |
https://qiita.com/REQWARE/items/c01a3e382629c85722ab
|
また、便利な機能として、印刷ダイアログの直接出力やPDFダウンロード機能などがあります。 |
2021-12-21 17:29:02 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
ボックス内にテキストや要素がない場合非表示にする方法 |
https://teratail.com/questions/374908?rss=all
|
ボックス内にテキストや要素がない場合非表示にする方法ボックスというと適切な表現ではないかもしれませんが、こちらの画像のような形にしたいのですがうまくいきません。 |
2021-12-21 17:35:43 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
box-shadowのinsetが適用されない |
https://teratail.com/questions/374907?rss=all
|
boxshadowのinsetが適用されない発生している問題imgの内側にぼかしとして適用したいのですが、boxshadowのinsetだけ適用されません。 |
2021-12-21 17:35:01 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
Pythonでscikit-learnのインストールエラー |
https://teratail.com/questions/374906?rss=all
|
Pythonでscikitlearnのインストールエラー前提・実現したいことPython初心者です。 |
2021-12-21 17:31:09 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
vscodeでlatexファイルのコンパイルをしてもpdfなどが作成されない |
https://teratail.com/questions/374905?rss=all
|
|
2021-12-21 17:28:19 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
virtualbox ブリッジアダプタ接続できない |
https://teratail.com/questions/374904?rss=all
|
ネットワークはブリッジアダプタに設定しています。 |
2021-12-21 17:21:51 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
node-sassの問題でrailsアプリをデプロイできない |
https://teratail.com/questions/374903?rss=all
|
nodesassの問題でrailsアプリをデプロイできない既存のrailsアプリをherokuにpushしたところエラーが発生してデプロイすることができません。 |
2021-12-21 17:21:47 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
kubectl minikubeを使ってブラウザからAngularアプリケーションへアクセスしたい |
https://teratail.com/questions/374902?rss=all
|
kubectlminikubeを使ってブラウザからAngularアプリケーションへアクセスしたいKubernetesの勉強をしているものです。 |
2021-12-21 17:11:51 |
Ruby |
Rubyタグが付けられた新着投稿 - Qiita |
[py2rb] re.finditer 2 |
https://qiita.com/superrino130/items/09f89dbb90b2056b7541
|
pyrbrefinditerはじめに移植やってますrefinditerPythonimportrerulerKRPltWKPltMRPsequenceMRGETGVSIKNPRPSRPFSCFWRKGDVENIRKSDIGNEKKIDAKFNRLQYNLYYKPLSHHKAGLLYKELFFRSCFSYTTCSLDFQGKRHQVERKAVDIVLprintxendforxinrefinditerrulesequenceどうするRubyNGrbruleKRPltWKPltMRPsequenceMRGETGVSIKNPRPSRPFSCFWRKGDVENIRKSDIGNEKKIDAKFNRLQYNLYYKPLSHHKAGLLYKELFFRSCFSYTTCSLDFQGKRHQVERKAVDIVLpsequencescanruleflattencompactmapsequenceindexsizescanは正規表現ですが、indexは単純な検索なんですね。 |
2021-12-21 17:25:40 |
AWS |
AWSタグが付けられた新着投稿 - Qiita |
AWS シリアルコンソールをFreeBSDで使う。 |
https://qiita.com/asakawaya/items/820a06856280413966c5
|
許可した後は、ECシリアルコンソールをクリックするとコンソールが開きます。 |
2021-12-21 17:45:34 |
Linux |
CentOSタグが付けられた新着投稿 - Qiita |
CentOS 8からMIRACLE LINUXに移行するのはちょっと待って(2021-12-21現在) |
https://qiita.com/error_401/items/f5fb50281eb0866b0fc2
|
CentOSからMIRACLELINUXに移行するのはちょっと待って現在現在の話です。 |
2021-12-21 17:39:39 |
技術ブログ |
Mercari Engineering Blog |
WebFrontendローカルパフォーマンス改善支援ツールを作ってみた。 |
https://engineering.mercari.com/blog/entry/20211217-856683a917/
|
hellip |
2021-12-21 09:00:29 |
技術ブログ |
Developers.IO |
API Gateway API へのエイリアスに表示されるドメイン名はどこで設定した値なのか |
https://dev.classmethod.jp/articles/find-an-alias-for-the-api-gateway/
|
apigatewayapi |
2021-12-21 08:49:56 |
技術ブログ |
Developers.IO |
Cloudformationのテンプレートに使える関数をまとめてみました ( 1 ) |
https://dev.classmethod.jp/articles/lim-cloudformation-function-1/
|
cloudformation |
2021-12-21 08:49:21 |
技術ブログ |
Developers.IO |
この先生きのこる人事評価される側の処世術 |
https://dev.classmethod.jp/articles/kinokoru-evaluation/
|
人事評価 |
2021-12-21 08:40:32 |
技術ブログ |
Hatena::Engineering |
はてなリモートインターンシップ2021のレポートサイトを公開しました |
https://developer.hatenastaff.com/entry/2021/12/intern-report
|
はてなリモートインターンシップのレポートサイトを公開しましたCTOのidmotemenです。 |
2021-12-21 17:29:46 |
海外TECH |
MakeUseOf |
How to Set Up Legacy Contacts to Pass On Your iCloud Data When You Die |
https://www.makeuseof.com/how-to-set-up-legacy-contacts-ios/
|
contacts |
2021-12-21 08:28:06 |
海外TECH |
DEV Community |
Create an animated sidebar with TailwindCSS in React💫 |
https://dev.to/byteslash/create-an-animated-sidebar-with-tailwindcss-in-react-1kjc
|
Create an animated sidebar with TailwindCSS in ReactHey everyone in many apps you need a sidebar drawer which slides in if you click on a hamburger icon In this tutorial we are going to see how to build that DemoVideo SetupCreating a new react app npx create react app animated sidebar Setting up tailwindCSSInstalling Tailwind npm install D tailwindcss postcss autoprefixernpx tailwindcss init pConfiguring paths Inside tailwind config jd replace the content with this module exports content src js jsx ts tsx theme extend plugins Add tailwindCSS to CSSIn index css add this code block tailwind base tailwind components tailwind utilities Creating the sidebar Making a new componentI am going to create a separate component for Sidebar so create a file Sidebar js in the src folder Now create a functional component const Sidebar gt return lt div gt lt div gt export default Sidebar Rendering the Sidebar componentWe also need to render the component so add this in App js import Sidebar from Sidebar function App return lt div className flex flex col items center justify center min h screen py gt lt Sidebar gt lt div gt export default App This should show us an empty canvas now Making a basic sidebarI am going to make a simple div with a text in it lt div className top right w vw bg blue p pl text white fixed h full gt lt h className mt text xl font semibold text white gt I am a sidebar lt h gt lt div gt This will give us a simple blue sidebar on the right side Handling open and closed statesCreate a useState to store a boolean value that decides if we should or shouldn t show the sidebar const showSidebar setShowSidebar useState false We also need to show buttons icons to open and close the sidebar so I will wrap the whole thing in a fragment add a button to close and a hamburger icon to open lt gt showSidebar lt button className flex text xl text white items center cursor pointer fixed right top z onClick gt setShowSidebar showSidebar gt x lt button gt lt svg onClick gt setShowSidebar showSidebar className fixed z flex items center cursor pointer right top fill EB viewBox width height gt lt rect width height gt lt rect gt lt rect y width height gt lt rect gt lt rect y width height gt lt rect gt lt svg gt lt div className top right w vw bg blue p pl text white fixed h full z gt lt h className mt text xl font semibold text white gt I am a sidebar lt h gt lt div gt lt gt This will not make any difference right now but let s add some conditional classes to the main sidebar div lt div className top right w vw bg blue p pl text white fixed h full z showSidebar translate x translate x full If the showSidebar variable is true then it will add the translate x otherwise translate x full Our sidebar now works VideoBut it isn t smooth so let us see how to make the animation smooth Just add these two classes to the blue div ease in out duration The div should look like this now lt div className top right w vw bg blue p pl text white fixed h full z ease in out duration showSidebar translate x translate x full gt lt h className mt text xl font semibold text white gt I am a sidebar lt h gt lt div gt Our sidebar animation looks very smooth and great VideoHope you liked this tutorial and add nice animation to the sidebar in your project Peace ️ Useful linksGitHub repoAnimate and Change Header Background on ScrollConnect with me |
2021-12-21 08:37:38 |
海外TECH |
DEV Community |
How to add login authentication to a Flask and React application. |
https://dev.to/nagatodev/how-to-add-login-authentication-to-a-flask-and-react-application-23i7
|
How to add login authentication to a Flask and React application In flask adding authentication has been made quite easy with the login required decorator in the flask extension Flask login I have an article on how to add basic authentication to your flask application that you can read up on hereHowever since you will be working with API endpoints you can t use the approach above because the login required decorator redirects to the application to an HTML page when it discovers a user that is not authenticated trying to access a protected page This defeats the idea of creating API endpoints as APIs are only designed to return data in json format In this part of the series you ll be learning how to add authentication to the connected React and Flask application you built in the previous part of the series Authentication will be done with the flask extension flask jwt extended Prerequisites Beginner level understanding of the flask framework If you are new to Flask you can check out my article on how to set up your flask project and use it with the jinja template engine I strongly advise you to read the previous article You can also get the files in the Github repo Familiarity with the basics of ReactJs You will be making use of the useState hook fetching data from API endpoints using axios and also using react router dom to handle routing of components Let s get started Flask Backend Installing the flask extension Navigate into the backend directory and run pip install flask jwt extendednote If you cloned the repo you don t need to run the command above just set up your flask application with the instructions in the README md file base pyYou ll be adding authentication to the profile API endpoint created in the previous tutorial Navigate to the base py script you created in the backend directory of your application to create the token login and logout API endpoints token login API endpointfrom flask import Flask request jsonifyfrom datetime import datetime timedelta timezonefrom flask jwt extended import create access token get jwt get jwt identity unset jwt cookies jwt required JWTManagerapi Flask name api config JWT SECRET KEY please remember to change me jwt JWTManager api api route token methods POST def create token email request json get email None password request json get password None if email test or password test return msg Wrong email or password access token create access token identity email response access token access token return response api route profile def my profile response body name Nagato about Hello I m a full stack developer that loves python and javascript return response bodyLet s go through the code above First the required functions are imported from the installed flask jwt extended extension from flask jwt extended import create access token get jwt get jwt identity unset jwt cookies jwt required JWTManagerNext the flask application instance is configured with the JWT secret key then passed as an argument to the JWTManager function and assigned to the jwt variable api config JWT SECRET KEY please remember to change me jwt JWTManager api The token API endpoint will have a POST request method Whenever the user submits a login request the email and password are extracted and compared with the hardcoded email test and password test Please note that in an ideal scenario you are going to compare the extracted login details with data in your database If the login details are not correct the error message Wrong email or password with the status code which means UNAUTHORIZED Error is sent back to the user return msg Wrong email or password Else if the login details are confirmed to be correct an access token is created for that particular email address by assigning the email to the identity variable Finally the token is returned to the user access token create access token identity email response access token access token return responseTo test this start your backend server withnpm run start backendPlease note that the command above was specified in the package json file in the react frontend This was done in the previous part of the series If you have not checked it out yet please head there so you can learn how to set it up However if you have already cloned the repo let s proceed Next open up postman and send a POST request to this API endpoint http tokenYou ll get a internal server error Check your terminal and you ll see the error as well AttributeError NoneType object has no attribute get the error occurred because you did not specify the login details when you made the POST request to the API endpoint thus a None value was passed as an argument to the request json get function Return to POSTMAN and pass the login details along with the POST request Please ensure you adjust your settings as circled in the image above After making the request you should get your access token in the form access token your access token will be here You can try to pass in a wrong email or password to see the UNAUTHORIZED error Logout API endpoint api route logout methods POST def logout response jsonify msg logout successful unset jwt cookies response return responseWhen the logout API endpoint is called response is passed to the unset jwt cookies function which deletes the cookies containing the access token for the user and finally returns the success message to the user Head over to Postman once again and make a POST request to the logout API endpoint http logoutYou should get the response below Refreshing tokensThe generated token always has a lifespan after which it expires To ensure that this does not happen while the user is logged in you have to create a function that refreshes the token when it is close to the end of its lifespan First specify the lifespan for your generated tokens and add it as a new configuration for your application Note You can change the time to suit your application api config JWT ACCESS TOKEN EXPIRES timedelta hours Then create the function below above the create token function api after requestdef refresh expiring jwts response try exp timestamp get jwt exp now datetime now timezone utc target timestamp datetime timestamp now timedelta minutes if target timestamp gt exp timestamp access token create access token identity get jwt identity return response except RuntimeError KeyError Case where there is not a valid JWT Just return the original respone return responseThe after request decorator ensures that the refresh expiring jwts function runs after a request has been made to the protected API endpoint profile The function takes as an argument the response from the profile API call Then the current expiry timestamp for the user s token is obtained and compared with the specified timestamp for the token which is set at minutes You can change this as well If the expiry timestamp for the user s token happens to be minutes away from expiration the token for that user is changed to a new one with the specified hr lifespan and the new token is returned to the user But if the token is not close to expiration the original token is sent to the user To conclude the backend setup you need to add the jwt required decorator to the my profile function to prevent unauthenticated users from making requests to the API endpoint But first test the profile API endpoint by making a GET request to the URL below using Postman http profileYou should still get the json form of the dictionary created in the last article Next add the jwt required decorator api route profile jwt required new linedef my profile response body name Nagato about Hello I m a full stack developer that loves python and javascript return response bodyand try to make the API request to the profile endpoint using the URL above You ll get a UNAUTHORIZED error because the token was absent when you made the request After the user logs in and gets the assigned token the token needs to be sent with each call the user makes to the API endpoints in the backend as an Authorization Header in this format Authorization Bearer lt access token gt Before you head over to the frontend you can also test this on Postman by adding the user s token to the Authorization header before you call the protected profile API endpoint Make a POST request to the endpoint below to get your token and copy it out http tokenNext add the authorization header key with your token as its value and then send the GET request you should get a json response containing the dictionary with your name and about me info Congratulations you have successfully added authentication to your API endpoint After the changes and additions this should be the final look of the base py script from flask import Flask request jsonifyfrom datetime import datetime timedelta timezonefrom flask jwt extended import create access token get jwt get jwt identity unset jwt cookies jwt required JWTManagerapi Flask name api config JWT SECRET KEY please remember to change me api config JWT ACCESS TOKEN EXPIRES timedelta hours jwt JWTManager api api after requestdef refresh expiring jwts response try exp timestamp get jwt exp now datetime now timezone utc target timestamp datetime timestamp now timedelta minutes if target timestamp gt exp timestamp access token create access token identity get jwt identity return response except RuntimeError KeyError Case where there is not a valid JWT Just return the original respone return response api route token methods POST def create token email request json get email None password request json get password None if email test or password test return msg Wrong email or password access token create access token identity email response access token access token return response api route logout methods POST def logout response jsonify msg logout successful unset jwt cookies response return response api route profile jwt required def my profile response body name Nagato about Hello I m a full stack developer that loves python and javascript return response bodyNow you can head over to the react frontend where you ll be making the API endpoint calls React FrontendIn the last article you only had to make a few changes to the App js file But this time around major changes will be made and new components will also be created In the frontend a Login component that will hold the login page will be created This component will be rendered anytime it notices that an unauthenticated user is trying to access a page that contains a protected API endpoint This will ensure that any request made to the backend has a token appended to it To start with create a new directory components in the src directory and in it four new components Login js useToken js Header js and Profile js Then navigate back to the base directory and install react router dom before you go into the components npm install react router dom Storage of token in the frontendThe token generated from the backend needs to be stored in your web browser after you log in Presently that is not the case Whenever a user refreshes his browser page the token gets deleted and the user would be prompted to log in once again To fix this you ll need to make use of web storage objects localStorage or sessionStorage You can read more on that here i sessionStorage The user s token gets stored in the tab currently opened in the browser If the user refreshes the page the token is still retained However if the user opens a new tab to the same page in the web browser the token won t reflect on that page as the new tab doesn t share the same storage with the previous one Thus the user would be prompted to log in again To see this in action open any website of your choice and open up the Developer tools menu with the Inspect Element or Inspect option by right clicking on any page in your browser You can also see the web storage under the Application section Open up your console and store an object sample in the web storage using the sessionStorage function sessionStorage setItem test Then to get the value assigned to the key test above run sessionStorage getItem test Refresh the page and run the getItem function again you ll still get the value from the storage Now open the link to the same page you just worked with in a new tab and try to access the stored object value via the console sessionStorage getItem test You ll get a null value because the current tab doesn t have access to the storage of the previous tab note while carrying out all the tests above keep an eye on the changes occurring in the web storage section above your console ii localStorage Here the user s token get s stored in universal storage that can be accessed by all tabs and browser windows The token is still retained even if the user refreshes or closes the page creates a new tab or window or restarts the browser entirely localStorage setItem test Then to get the assigned value localStorage getItem test Try to run the duplicate test done above you ll notice that you can access the value from the duplicated page You can also create a new browser window open any page of the same website and try to access the value set above You ll notice that you still have access to it That is the beauty of using localStorage it ensures that the user only needs to log in once and they can easily navigate to any page on the website Whenever you are done you can delete the object from the storage using localStorage removeItem token useToken jsNow you need to replicate what was done above in your react code Open the useToken component import useState from react function useToken function getToken const userToken localStorage getItem token return userToken amp amp userToken const token setToken useState getToken function saveToken userToken localStorage setItem token userToken setToken userToken function removeToken localStorage removeItem token setToken null return setToken saveToken token removeToken export default useToken With the tests you carried out in the console the functions created in the useToken component should be easy to understand The getToken function is used to retrieve the token stored in the localStorage and only returns a token if it exists hence the use of the amp amp conditional operator The useState hook is used to handle the state of the token variable which will contain the value of the token This ensures that the react application always reloads when any of the functions are called Such that when a user logs in and the token is stored or when the user logs out the application also becomes aware that a change has occurred in the web storage of your browser and hence reacts accordingly by either redirecting to the page the user wants to access or returning to the login page once the user logs out The saveToken function handles the storage of the token obtained when the user logs in and the setToken function in it updates the state of the token variable with the token passed as an argument to the saveToken function The removeToken function deletes the token from the local storage and returns the token back to the null state whenever it gets called Finally the saveToken function assigned as a value to the setToken variable the value of the token itself and the removeToken function are all returned as the result of calling the useToken function App jsI told you that you ll be making major changes right Clean up App js all the code that was added the last time will be moved into the Profile component import BrowserRouter Route Routes from react router dom import Login from components Login import Profile from components Profile import Header from components Header import useToken from components useToken import App css function App const token removeToken setToken useToken return lt BrowserRouter gt lt div className App gt lt Header token removeToken gt token amp amp token amp amp token undefined lt Login setToken setToken gt lt gt lt Routes gt lt Route exact path profile element lt Profile token token gt gt lt Route gt lt Routes gt lt gt lt div gt lt BrowserRouter gt export default App At the top of the file the BrowserRouter Route Routes functions that will be used to handle URL routing for the profile component are imported from the installed react router dom package The other created components are also imported from the components folder In the App function the value object returned when the useToken function is called is destructured and the values are assigned to the token removeToken and setToken variables respectively const token removeToken setToken useToken Next the BrowserRouter function is made the parent component and in it the Header component is placed with the removeToken function passed as an argument which is called prop in react lt Header token removeToken gt Then the javascript conditional ternary operator is used to ensure that the user must have a token before having access to the profile component If the user doesn t have a token the Login component is rendered with the setToken function passed as an argument Else if the user already has a token the Profile component with the URL path profile is rendered and displayed to the user You can read more on how to use React Router hereNow you need to create the Login Header and Profile functions in your Login Header and Profile component files respectively Login jsimport useState from react import axios from axios function Login props const loginForm setloginForm useState email password function logMeIn event axios method POST url token data email loginForm email password loginForm password then response gt props setToken response data access token catch error gt if error response console log error response console log error response status console log error response headers setloginForm email password event preventDefault function handleChange event const value name event target setloginForm prevNote gt prevNote name value return lt div gt lt h gt Login lt h gt lt form className login gt lt input onChange handleChange type email text loginForm email name email placeholder Email value loginForm email gt lt input onChange handleChange type password text loginForm password name password placeholder Password value loginForm password gt lt button onClick logMeIn gt Submit lt button gt lt form gt lt div gt export default Login The code above should be easy to understand the summary of what it does is to use the login details provided by the user to make a POST request to the token API endpoint in the backend which then returns the user s token and the token is stored in the local web storage using the setToken function passed as a prop to the Login function Header jsimport logo from logo svg import axios from axios function Header props function logMeOut axios method POST url logout then response gt props token catch error gt if error response console log error response console log error response status console log error response headers return lt header className App header gt lt img src logo className App logo alt logo gt lt button onClick logMeOut gt Logout lt button gt lt header gt export default Header Once the user clicks on the Logout button a POST request is made to the logout API endpoint and the cookies in which the user s JWToken is stored are cleared on the backend The Axios response function is used to call the removeToken function which deletes the token stored in the local web storage Now if the user tries to access the profile page the user gets redirected to the login page Profile jsimport useState from react import axios from axios function Profile props const profileData setProfileData useState null function getData axios method GET url profile headers Authorization Bearer props token then response gt const res response data setProfileData profile name res name about me res about catch error gt if error response console log error response console log error response status console log error response headers return lt div className Profile gt lt p gt To get your profile details lt p gt lt button onClick getData gt Click me lt button gt profileData amp amp lt div gt lt p gt Profile name profileData profile name lt p gt lt p gt About me profileData about me lt p gt lt div gt lt div gt export default Profile The piece of code previously in App js was moved here This contains the protected endpoint profile A GET request method is sent to the endpoint whenever the Click me button is clicked and it responds with the user s details For the user to be able to access the data of the profile API endpoint an Authorization header that contains the token must be added to the axios GET request headers Authorization Bearer props token App cssYou also need to make a change to the CSS style for the header On line you ll see the style for the header component App header Comment out or delete the min height vh code so your application can end up looking like Now to test your application start the backend server by running the script belownpm run start backendfollowed by npm startThen navigate to the http localhost profile URL in your web browser and you ll be prompted to login since the page is protected I hope you still remember the login details email test and password test You can also open up localStorage under the Application section in Developer tools to monitor the token as it gets stored and deleted It s been a long ride but we have finally come to the end of this tutorial With what you have learned I believe you can easily authenticate your flask plus react applications Congratulations on the new knowledge you just acquired If you have any questions feel free to drop them as a comment or send me a message on Linkedin or Twitter and I ll ensure I respond as quickly as I can Ciao |
2021-12-21 08:14:51 |
海外TECH |
Engadget |
T-Mobile says it blocked 21 billion scam calls in 2021 |
https://www.engadget.com/t-mobile-said-it-blocked-21-billion-scam-calls-in-2021-085409908.html?src=rss
|
T Mobile says it blocked billion scam calls in T Mobile announced that scam call traffic more than doubled in with attempts hitting an average of million calls every week Bleeping Computer reported It also said that it blocked over billion of those calls for T Mobile customers through December over calls per second via its Scam Shield service Over half the billion calls were related to fake vehicle warranty scams while others impersonated Social Security employees wireless providers car insurance companies and package delivery Scammers preferred locations were Texas Florida Arizona and Georgia with the most targeted area code being the Dallas Fort Worth area nbsp T Mobile launched its Scam Shield service last year promising protection for all users regardless of their plan You can choose to either screen calls as quot scam likely quot when a call comes in or block them altogether using a variety of methods as T Mobile details in its blog post nbsp AT amp T and Verizon also released stats for scam calls with AT amp T saying its ActiveArmor service has blocked over billion suspicious calls since Verizon meanwhile revealed that around million of its customers were protected from billion unwanted calls by its Verizon Call Filter service nbsp |
2021-12-21 08:54:09 |
海外科学 |
NYT > Science |
SpaceX Reports 132 Covid Cases at Headquarters in California |
https://www.nytimes.com/2021/12/20/science/spacex-covid-cases.html
|
astronaut |
2021-12-21 08:56:05 |
金融 |
JPX マーケットニュース |
[OSE]東証マザーズ指数構成銘柄の一部除外 |
https://www.jpx.co.jp/news/2020/20211221-01.html
|
東証マザーズ指数 |
2021-12-21 18:00:00 |
金融 |
金融庁ホームページ |
職員を募集しています。(金融庁における国際関連業務に従事する職員(課長補佐級)) |
https://www.fsa.go.jp/common/recruit/r3/soumu-08/soumu-08.html
|
課長補佐 |
2021-12-21 10:00:00 |
ニュース |
ジェトロ ビジネスニュース(通商弘報) |
入国後の隔離期間を短縮、ワクチン接種者は3日間に |
https://www.jetro.go.jp/biznews/2021/12/837f5d8cb443d712.html
|
隔離 |
2021-12-21 08:15:00 |
海外ニュース |
Japan Times latest articles |
Huge quake off northern Japan could cause 199,000 deaths, government warns |
https://www.japantimes.co.jp/news/2021/12/21/national/potential-quake-damage-estimate-report/
|
damage |
2021-12-21 17:56:47 |
海外ニュース |
Japan Times latest articles |
Ivermectin for COVID? Unproven treatment stokes concern in Japan |
https://www.japantimes.co.jp/news/2021/12/21/national/ivermectin-japan-covid19-little-evidence/
|
Ivermectin for COVID Unproven treatment stokes concern in JapanAlthough the treatment has received some support from Japan s medical establishment and studies are ongoing ivermectin is not approved as a COVID remedy in the |
2021-12-21 17:06:01 |
海外ニュース |
Japan Times latest articles |
A fond farewell to two musical inspirations |
https://www.japantimes.co.jp/opinion/2021/12/21/commentary/world-commentary/honoring-musical-inspirations/
|
shakespeare |
2021-12-21 17:17:07 |
海外ニュース |
Japan Times latest articles |
Not everyone is sold on the new U.S. ambassador to Japan |
https://www.japantimes.co.jp/opinion/2021/12/21/commentary/new-u-s-japan-ambassador/
|
Not everyone is sold on the new U S ambassador to JapanEmanuel s appointment is worrisome for Japan which desires the ambassadors sent to Tokyo to have influence and support in their home governments something he does |
2021-12-21 17:15:48 |
ニュース |
BBC News - Home |
Covid: Firms urge PM for clarity on restrictions over Christmas |
https://www.bbc.co.uk/news/uk-59736716?at_medium=RSS&at_campaign=KARANGA
|
england |
2021-12-21 08:06:30 |
ニュース |
BBC News - Home |
Covid: All sports events in Wales go behind closed doors |
https://www.bbc.co.uk/news/uk-wales-politics-59729129?at_medium=RSS&at_campaign=KARANGA
|
games |
2021-12-21 08:50:22 |
ニュース |
BBC News - Home |
Scottish Power debt team filmed raiding wrong home |
https://www.bbc.co.uk/news/uk-scotland-59733043?at_medium=RSS&at_campaign=KARANGA
|
power |
2021-12-21 08:36:37 |
ニュース |
BBC News - Home |
Immensa: Month delay before incorrect Covid tests halted |
https://www.bbc.co.uk/news/uk-england-somerset-59730888?at_medium=RSS&at_campaign=KARANGA
|
september |
2021-12-21 08:32:50 |
ニュース |
BBC News - Home |
Omicron: What are the new Covid rules for the UK? |
https://www.bbc.co.uk/news/explainers-52530518?at_medium=RSS&at_campaign=KARANGA
|
omicron |
2021-12-21 08:39:16 |
ビジネス |
ダイヤモンド・オンライン - 新着記事 |
ユーグレナ(2931)、2021年12月末の株主優待の内容 を発表! 100株以上で自社商品が割引になる専用カタ ログや「からだにユーグレナGreen Powder」を贈呈 - 株主優待【新設・変更・廃止】最新ニュース |
https://diamond.jp/articles/-/291507
|
ユーグレナ、年月末の株主優待の内容を発表株以上で自社商品が割引になる専用カタログや「からだにユーグレナGreenPowder」を贈呈株主優待【新設・変更・廃止】最新ニュースユーグレナが、「年月末」時点の株主に実施する株主優待の内容を、年月日に発表した。 |
2021-12-21 17:50:00 |
ビジネス |
不景気.com |
福岡の宿泊・研修施設運営「直方」に破産開始決定 - 不景気.com |
https://www.fukeiki.com/2021/12/nogata-ikoi-mura.html
|
株式会社 |
2021-12-21 08:06:28 |
北海道 |
北海道新聞 |
わいせつ教員200人処分 20年度、文科省調査 |
https://www.hokkaido-np.co.jp/article/625705/
|
調査 |
2021-12-21 17:17:00 |
北海道 |
北海道新聞 |
災害時にコンテナホテル、熊本 避難所活用へ協定 |
https://www.hokkaido-np.co.jp/article/625696/
|
避難所 |
2021-12-21 17:17:00 |
北海道 |
北海道新聞 |
鈍器で乗客殴打、女逃走 横浜の地下鉄車内、軽傷 |
https://www.hokkaido-np.co.jp/article/625698/
|
横浜市内 |
2021-12-21 17:17:00 |
北海道 |
北海道新聞 |
NFL、レイダーズが競り勝つ ブラウンズに16―14 |
https://www.hokkaido-np.co.jp/article/625704/
|
共同 |
2021-12-21 17:17:00 |
北海道 |
北海道新聞 |
全国スーパー売上高、2・8%増 11月、食料品や総菜堅調 |
https://www.hokkaido-np.co.jp/article/625697/
|
全国スーパー売上高 |
2021-12-21 17:02:00 |
マーケティング |
MarkeZine |
ニールセンが2021年日本のンターネットサービス利用者数/利用時間ランキングを発表 |
http://markezine.jp/article/detail/38022
|
時間 |
2021-12-21 17:30:00 |
IT |
週刊アスキー |
地元産の小麦を使用! 横浜ビール、人気のクラフト缶ビール2種をローソン限定販売 |
https://weekly.ascii.jp/elem/000/004/078/4078581/
|
数量限定 |
2021-12-21 17:30:00 |
IT |
週刊アスキー |
PS4/Switch『屍喰らいの冒険メシ』のウェブコンテンツ「冒険者メーカー」を公開! |
https://weekly.ascii.jp/elem/000/004/078/4078591/
|
nintendo |
2021-12-21 17:20:00 |
コメント
コメントを投稿