한국어

Coding

온누리070 플레이스토어 다운로드
    acrobits softphone
     온누리 070 카카오 프러스 친구추가온누리 070 카카오 프러스 친구추가친추
     카카오톡 채팅 상담 카카오톡 채팅 상담카톡
    
     라인상담
     라인으로 공유

     페북공유

   ◎위챗 : speedseoul


  
     PAYPAL
     
     PRICE
     

pixel.gif

    before pay call 0088 from app


https://stormpath.com/blog/tutorial-build-rest-api-mobile-apps-using-node-js


Behind every great mobile app is a great backend, but building a REST API for your app can be a bit daunting if you haven’t done so before. Fear not! This tutorial will show you how to build your first REST API using Node.js, and connect it to an iOS or Android app!

As a mobile app developer, I love to build REST APIs using the Node.js backend for several reasons:

  • It’s easy to work with JSON in JavaScript, because JSON stands for JavaScript Object Notation!
  • Node.js is lightweight and easy to get started with.
  • Node.js gives you fine-grained control over your request and responses.

However, when building an API, figuring out how to handle authentication is always a huge challenge. Authentication refers to the practice of understanding exactly who is accessing your data, and securely doing so is not easy. We built Stormpath to help developers easily add secure authentication to their apps, and we’ll also show you how to include this in your Node.js-powered REST API.

Node.js and Express for Android & iOS

Today, we’ll build the backend powering Stormpath Notes, a simple note taking app that syncs data online. With this knowledge, maybe you’ll be able to build a solid competitor to Evernote, OneNote, and other industry giants!

We have a separate tutorial for how to build the iOS and Android apps that can use this backend, so check them out once you’ve finished this tutorial.

Today we’ll be implementing the following endpoints:

GET /notes – returns the notes for the authenticated user in the form of a JSON object.

POST /notes – takes a JSON object with the notes and saves it for the authenticated user.

The JSON object takes the form of:

Stormpath’s backend integrations (Express-Stormpath being one of them) also expose a common API, including /register/oauth/token (for logging in), and other endpoints so we don’t have to worry about coding them! You’ll learn more about those endpoints later in this tutorial.

We’ll also be using the following tools to build and test this backend:

  • Node.js – the runtime for our app.
  • Express.js – a popular, lightweight framework for building Node.js apps
  • Stormpath – a backend service for handling user authentication
  • Postman – a HTTP client that allows us to make custom requests to the REST API

Also, the finished code is live and hosted at https://stormpathnotes.herokuapp.com/, so you can play around with the API, and the code is available on GitHub

Starting Your Node.js Mobile App

To get started, make sure that you:

  1. Install a great text editor. I like SublimeAtom, or VS Code
  2. Install the Node.js runtime. You can install the “Current” (v6) version of Node.
  3. Sign up for a Stormpath Account
  4. Install Postman

Setting Up Your App

To get started with your Node.js project, we’ll use npm. npm is a package manager for JavaScript projects, and allows you to install JavaScript tools and modules for your project. It’s automatically included in your Node.js install, so all we have to do is start using it in the command line!

To get started, create a folder, navigate to it in the command line, and run:

npm will ask you a lot of questions — feel free to leave them as the default!

Once you’re done, npm will create a package.json file in your folder. package.json keeps track of your project information and dependencies!

In addition, we need to install express, a popular, minimalist web framework for Node.js. Install it by running this command:

With this command, npm will install express, and save its version to the package.json file. Now, we can use express in our project.

Code Your First REST API

We’re all set with the project, so let’s start writing our REST API! Create a file named index.js, and type in the following:

Simple, right? In six lines of code, we:

  • Imported the Express module
  • Initialized the Express object
  • Added a handler for GET /notes which responds to the request with a JSON object with sample notes
  • Told express to listen to HTTP requests on port 3000

Try running it in the command line:

Congrats, you now have a basic REST API with one endpoint, and it’s running on your machine! Try visiting it at http://localhost:3000/notes and see what happens.

REST API Endpoint

Adding Authentication to Your Mobile API

Having a /notes endpoint is great, but for a note-taking app, we can’t have everyone viewing the same set of notes. We need to add authentication to our app. Authentication allows our REST API to know who is accessing the notes endpoint, and only show notes to users that are logged in. For that, we’re going to use Stormpath.

Log into the Stormpath Account you created, and click on the Node.js quickstart. In the first page, you’ll see a section showing you how to set up your API Keys by using environment variables. Environment variables allow you to configure your application without using code, which is great when you have multiple development environments or even servers. Paste the API Keys from the quickstart into your command line:

Let’s install the express-stormpath integration, so we can get a standard API for logging in, and other tasks:

Now, let’s add Stormpath to our application in index.js:

Delete the old code for the /notes endpoint, and replace it with:

In this bit of code, we’re initializing express-stormpath and attaching it to Express. We’re asking it to preload user customData when retrieving objects from Stormpath. We need customData to store our user’s notes, and this will make them easier to fetch. In addition, we configure it to only produce application/json outputs, as otherwise it can also produce HTML views. Express-Stormpath is highly configurable, and supports many different options for building your API.

To require authentication, we’re attaching the stormpath.apiAuthenticationRequired middleware to the /notes endpoint. This will inspect the headers on every request, and look for an access token. If there is no access token, it will respond with a 401 Unauthorized error.

Finally, we respond with the notes in the customData, or, if not present, a default message for your notes.

Let’s run this code, and try using our new API. But this time, instead of using a browser, we’re going to use Postman.

Testing Your Node.js REST API With Postman

To get started with Postman, let’s try registering a new user in our app. To do this, let’s first install the Stormpath Notes Postman collection. This will add pre-made requests to your Postman app, which will make it easier for you to test out your API.

Register Account Using Postman

Make sure that your server is running, and then click and send the “Register New User” request in Postman. This will load a saved request for the /register route. Feel free to click around, and see what Postman is sending to /register. If you click “Send”, the server will return a JSON object of the new account. Congrats, you’ve just registered an account on your Stormpath instance! You can double check if the account has been registered in the Stormpath Admin Dashboard.

Getting an OAuth 2 Token

For mobile and web clients, Stormpath uses OAuth 2 access and refresh tokens for authentication. An access token is used for direct authentication with the API, but expires on a periodic basis. When the access token expires, the refresh token can be used to get a new access token. This makes your API more secure and scalable.

To get your OAuth 2 tokens, click on and send the “Get OAuth Tokens” request in Postman. You’ll see an access and refresh token pair pop out in JSON:

Getting the Notes

Now that we have our access token, let’s use it to authenticate a request to the API we’ve created. Open up the “Get Notes” request in Postman, and insert your access token into the Authorization header so it says:

Authorization: Bearer eyJraWQiOiIxTkk0SUg3ME9WN1Y3V...

Now run the request. You should see the default JSON response!

Authenticated REST API Endpoint

Saving the Notes To Your REST API

We’ve gotten and tested out three of our endpoints. It’s time to write the final endpoint, so the user can save the notes back to the server.

In the command line, run:

In our index.js file, add:

Express is a minimalist web framework, so to parse the POST body from our app, we need to add one more package. We use body-parser and bind it to the app as middleware. This means that every request will pass throughbody-parser, and body-parser will inspect the POST body, and add any JSON or urlencoded info to the request object as req.body.

Afterwards, we register a POST endpoint which reads the request body, verifies that the user passed a “notes” string, and saves it to our user’s customData in Stormpath.

Let’s restart the server and test it. Click on the “Save Notes” request in Postman, add your access token, modify the body to something else, and then make the request! Now, send the “Get Notes” request again. You should see that it’s now what you just saved! You can also see the data attached to the user’s customData in the Stormpath Admin Dashboard.

Congrats, you just finished this tutorial! Today, you learned how to write a basic Node.js application, integrate Stormpath, and write two endpoints to help you retrieve and save a user’s notes!

Next Steps

Check out the code on GitHub – Want to see the final version of Stormpath Notes? See Stormpath Notes on GitHub.

Try the iOS or Android Tutorial – Learn how to build Stormpath Notes on iOS using Swift or Android!

Learn More About Express-Stormpath – You’ve been using Express-Stormpath for today’s demo, but we’ve only scratched the surface regarding the features you can use it for. Check out our awesome documentation about how to use Express-Stormpath, or learn how to deploy Express-Stormpath to Heroku, so your API will be available to the public!

Read More on RESTful API Design – Vinny Sahni from Enchant wrote a great blog post about designing a pragmatic RESTful API. A must read if you’re building a REST API from scratch.

Talk to us! – We’re proud of the exceptional level of support we provide our community, and would love to hear from you about your project! Please don’t hesitate to contact us at support@stormpath.com, file an issue against one of our GitHub projects, or leave a comment below!

번호
제목
글쓴이
66 JavaScript & Node.js node 웹서버 구현 강의 설명 매우 잘됨 가장중요한 내용
admin
2019-11-20 9178
65 Node.js 익스프레스 웹 서버 Express-generator로 빠르게 설치하기
admin
2019-11-17 8547
64 [Express.js] Express 로 웹 애플리케이션 만들기 express 사용법
admin
2019-11-17 8516
63 [node.js] express, 웹서버 구축, 설계, 제작
admin
2019-11-17 8918
62 npm init 초기화
admin
2019-11-17 14024
61 Node.JS vhost 사용 설명
admin
2019-05-31 9169
60 How to build scalable node js and express website rest api
admin
2019-05-31 8534
59 Hosting multiple websites using NodeJS and Express 멀티 도메인 호스팅
admin
2019-05-31 8708
58 Node.js SSL / TLS 인증서 갱신 실제 적용 방법 초간단 설명 재발급
admin
2019-05-26 9087
57 node js 와 Jade 를 이용한 Database 를 홈페이지에 출력
admin
2018-06-23 10923
56 node.js로 서버를 구축하고 mysql을 데이터 베이스로 회원가입과 로그인 기능을 구현
admin
2018-06-23 18065
55 [Node.js] JWT(JSON Web Token)로 로그인 REST API 만들기 총 정리
admin
2018-06-14 13321
54 webstorm The smartest JavaScript IDE
admin
2018-06-02 10483
53 Node js 보안 Express
admin
2018-05-07 14416
52 안드로이드 배우기: REST API 사용하기
admin
2018-05-06 16732
51 Getting Started with REST: Consuming simple REST APIs in Android
admin
2018-05-06 10855
50 Android - JSON Parser JSONArray,JSONObject,JSONStringer JSONTokenizer
admin
2018-05-02 11114
49 GET & POST Requests in Node.js Using Express-4
admin
2018-04-30 11427
48 Writing middleware for use in Express apps
admin
2018-04-29 10514
47 Use ExpressJS to Get URL and POST Parameters
admin
2018-04-29 10790
46 body-parser Learn about the anatomy of an HTTP transaction in Node.js
admin
2018-04-29 10923
45 How to handle the POST request body in Node.js without using a framework
admin
2018-04-29 10906
44 How can I read the data received in application/x-www-form-urlencoded format on Node server?
admin
2018-04-29 11976
43 postman google
admin
2018-04-29 10162
42 How to set custom favicon in Express?
admin
2018-04-29 16164
41 serve-favicon install and how to
admin
2018-04-29 11033
40 'Express' is not recognized command (windows) 기초
admin
2018-04-28 11008
39 AWS 람다로 서버 없이 간단한 REST API 만들기
admin
2018-04-15 16875
38 Android Login Registration System with PHP and MySQL (Updated) – Reset Password #3
admin
2018-04-14 15659
37 Android Login Registration System with PHP and MySQL (Updated) – Client #2
admin
2018-04-14 13852
36 Android Login Registration System with PHP and MySQL (Updated) – Server #1
admin
2018-04-14 19585
35 Working with JSON in MySQL perfect
admin
2018-04-14 10029
34 MySQL Data Access API Development Using Express.JS, Node.JS
admin
2018-04-14 10272
33 How to connect to a MySQL database with Node.js
admin
2018-04-14 10777
32 Consuming a JSON REST API in Android
admin
2018-04-14 10790
31 NODE.JS REST API
admin
2018-04-14 10301
30 NODE.JS DATABASE MYSQL TUTORIAL
admin
2018-04-14 12735
29 How can I send a post request with JSON from Android to a Node.js server?
admin
2018-04-14 10114
28 How do I send data to a Node.js server from an Android app?
admin
2018-04-14 10408
27 Android User Registration and Login with Node.js and MongoDB – Server #1
admin
2018-04-14 14359
26 Node.js Parse JSON Little information to use JSON Data
admin
2018-04-14 10894
Build a REST API for Your Mobile Apps using Node.js
admin
2018-04-14 10038
24 Android Asynchronous Http Client A Callback-Based Http Client Library for Android
admin
2018-04-14 15606
23 RESTful Api using node.js,Express and Mysql
admin
2018-04-14 10334
22 노드에서 MySQL을 사용하는 방법 MySQL with Node.js and the mysql JavaScript Client
admin
2018-04-14 17115
21 Check that you have node and npm installed
admin
2018-01-16 9792
20 mongodb 설치
admin
2018-01-15 9848
19 node js 설치 install 리눅스 데비안
admin
2018-01-15 10547
18 nodejs windows 윈도우 노드 제이에스 설치 다운로드
admin
2018-01-15 10613
17 Node.js paypal PayPal-node-SDK 사용해보자 상세한설명 연습 사례
admin
2018-01-15 9970
16 Simple, unobtrusive authentication for Node.js passport facebook twitter gmail etc
admin
2018-01-07 9837
15 Your first Node.js HTTP server [ this chapter ]
admin
2018-01-07 9876
14 NodeJS - Setup a Simple HTTP Server Local Web Server
admin
2018-01-07 10179
13 NodeJS를 이용한 API 서버만들기 3 자세한 설명 잘됨 매우 좋음 기초 노드
admin
2017-12-24 11637
12 JSON. Using the JSONObject in android and java.
admin
2017-12-24 10087
11 Android PHP MySQL 데이터베이스에서 데이터를 JSON 형식으로 가져오기
admin
2017-12-24 23040
10 Android에서 REST 요청 후 JSON 응답 받기
admin
2017-12-24 12228
9 Node.js를 이용하여 MySQL 데이터 가져오기
admin
2017-12-24 23631
8 Node.js - mysql 연결
admin
2017-12-24 11831
7 RESTful Api using node.js,Express and Mysql
admin
2017-12-24 10725
6 Using MySQL with Node.js & the mysql JavaScript Client 매우 설명 잘됨 공부 좋음
admin
2017-12-24 22236
5 Android Login Registration System with Node.js and MongoDB – Server #1
admin
2017-12-24 31285
4 How to Setup Node.js and MongoDB in Ubuntu and Windows
admin
2017-12-24 11073
3 Build a REST API for Your Mobile Apps using Node.js
admin
2017-12-24 10712
2 MySQL version 5.7.8 introduces a JSON data type
admin
2017-12-24 10066
1 Best Practices|| 128- Connect Android to MYSQL use Node.JS
admin
2017-12-24 9608