简体   繁体   中英

Meteor JS how to create api for native app?

I am new in meteor js and web app is created in meteor. I need to create API's for mobile app and native and web app will share the same database. This is not clear to me from where I need to start to create API for the native app? This is my login route which I am using for the web app. Path of web app login route

 socialapp\socialappv1\app\lib\routes.js

 Router.route('login', {
   name: 'login',
   controller: 'LoginController',
   where: 'client'
 });

and to create API I have created a server.js file in socialapp\\socialappv1\\app\\server\\ directory and I am trying to create API to register a user.

Router.route('/register/',{where: 'server'})

.post(function(){
//console.log(this.request.body);
//return false;
let user = { 
email : this.request.body.email,
username : this.request.body.username,
password : this.request.body.password,

};

});
 const userId = Accounts.createUser(user);
 if(userId)
 {

    console.log("Register");
 }else{

    console.log("Not Register");
 }


});   

Is there any other way to create rest API eg to call controllers or is this correct to start API?

I think your code may be trying to set up client side routes (not sure which router you are using).

You need to add server side routes (and you can use express for this), and the handler needs to attach to the Meteor environment

This is some code I have written to handle payment confirmations coming to the server: (server side code of course)

import { Meteor } from 'meteor/meteor'
import express from 'express'
import bodyParser from 'body-parser'

const debug = require('debug')('b2b:server-payments')

async function acceptPayment(req, res) {
  // We need to bind to the Meteor environment for this to work.
  Meteor.bindEnvironment(() => {
    debug('/payment hook', req.body)
    try {
// Handle the data that's in req.body ...
  : 
  :
    } catch (e) {
      console.error(e)
    }
  })()

  res.status(200).json({ status: 'ok' }) // Change this if your data isn't JSON
}

export function setupPaymentsApi() {
  debug('Setting up payment hooks')
  const app = express()
  app.use(bodyParser.json({ extended: false }))

  app.post('/payment', acceptPayment)
  app.get('/api', (req, res) => {
    res.status(200).json({ message: 'B2B Payments API' }) // Shouldn't call this, just for testing for now
  })

  WebApp.connectHandlers.use(app)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM