如何保存服务器返回的值 [英] How to save returned value from a server

查看:48
本文介绍了如何保存服务器返回的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下Web服务在线托管,可以验证是否可以在系统中添加新用户.

I have the following web service that is hosted online and validates wheter or not we can add a new user into our system.

router.post('/register', (req, res) => {  
var user = req.body;   

var userPromise = new Promise(async (resolve, reject) => {
    resolve(await findBy("Users", "email", user.email.toLowerCase()));
})
.then(function(result){
    if (result){
        res.status(418).end(JSON.stringify("User already exists."));
        return;
    }

    var pass;
    var passPromise = new Promise(async (resolve, reject) => {
        resolve(await bcrypt.hashSync(user.password));
    })
    .then(function(result){
        var createPromise = new Promise(async (resolve, reject) => {
            try{
                await createUser(user.name, user.email.toLowerCase(), result); 
                resolve();
            }
            catch (err){
                reject();
            }            
        })
        .then(function(result){
            res.status(200).end(JSON.stringify("Signup successful."));
        })
        .catch(function(result){
            res.status(418).end(JSON.stringify("Failed to create user."));
        });
    }); 
});
});

有关更多详细信息,这里是此函数内部调用的方法.

For some extra detail here is the methods called inside this function.

function createUser (userName, userEmail, userPass, dev) {
var mg = require('mongodb').MongoClient;

mg.connect(url, { useNewUrlParser: true, useUnifiedTopology: true }, function(err, db){
    var dbo = db.db(myDB);
    var user = { name: userName, 
                 email: userEmail,
                 password: userPass,
                 devices: dev };

    var insert = util.promisify(dbo.collection("Users").insertOne);

    dbo.collection("Users").insertOne(user, function(err, res) {
        if (err) 
            throw err;

        console.log(`${user.name} has been added.`);
        db.close();

        sendEmail(userEmail, 
                  'The CRUST Company welcomes you!',
                  'Thank you for signing up for our services!' );
    });
});
}

 //See if a user exists
async function findBy (collection, queryField, value) {
var mg = require('mongodb').MongoClient;

return new Promise(function(resolve, reject) {
    mg.connect(url, { useNewUrlParser: true, useUnifiedTopology: true }, function(err, db) {
      if (err) 
        reject(err);  
      else 
        resolve(db);   
    });
})
.then((result) => {
    db = result;
    var dbo = db.db(myDB);
    var query = { };
    query[queryField] = value;

    var val = dbo.collection(collection).findOne(query);
    db.close();
    return(val);
})
.catch();
}

现在在我的主应用程序中,我希望能够调用方法寄存器,该方法寄存器将所需的信息传递到Web服务以进行验证,如果用户被接受,我必须导航至登录表单,并且系统返回错误我希望能够显示该错误.这是我目前拥有的代码.

Now within my main application I want to be able to call my method register that passes the needed information through to the web service for validation and if the user is accepted i must navigate to the login form and if the system returns an error I want to be able to display that error. Here is the code i currently have.

 register(postData: User): Observable<AuthResponse> {
 try {
    this.http.post<AuthResponse>(`https://1146c1fe.ngrok.io/register`, (postData)).pipe(
    tap(async (res: AuthResponse ) => {
      console.log('I am done.');
    })
  );
 } catch (err) {
   alert('Error.Error');
   console.log('Error.Error');
 }
 return;
}

我不确定在此阶段AuthResoponse类中必须包含什么内容,因此那里的任何建议都将有所帮助,并且如果用户被接受,则控制台中将打印我已完成",但是如果服务器说不,那么控制台中未显示任何消息.

I am unsure on what must be within the AuthResoponse class at this stage so any advice there would help and also if the user is accepted then the 'I am done' is printed in the console but if the server says no then then no message is displayed in the console.

因此,我只想简单地回顾一下错误消息并向用户显示错误消息,然后将其保留在此页面上.

So a brief recap i simply want to be able to catch and display the error messages to the user and then keep them on this page.

推荐答案

由于使用的是Ionic 4,因此应使用服务来定向HTTP请求.在此服务中,您应该处理传入的数据或传入的错误,并将它们传递回页面.auth.service中的函数是一个Observable,因此您可以订阅该函数以接收结果或错误.

register.page.ts
在指向AuthService的.ts文件中注册函数,并使用服务中提供的函数发出请求并接收响应或错误

Since you are using Ionic 4, you should use services to direct the HTTP requests. Inside this service, you should handle your incoming data or incoming error and pass them back to your page. The function in auth.service is an Observable, so you can subscribe to it to receive the result or the error.

register.page.ts
Register function in the .ts file which points to the AuthService and uses a function provided in the service to make the request and receive a response or an error

constructor(
  private authService: AuthService,
  // other stuff
) {}

register() {
  this.authService
    .register(data) // execute register function in auth.service
    .subscribe(
      result => { // your result from observer.next() in auth.service
        // success
      },
      error => { // your error from observer.error() in auth.service
        // no success
      }
    );
}

auth.service.ts
进行http发布呼叫,并从您的Web服务接收数据或错误,然后将它们传递给page.ts中的register()函数.

auth.service.ts
Make the http post call and receive data or errors from your webservice and pass them to your register() function in page.ts

register(data): Observable<any> {
  return new Observable(observer => {
    this.http.post(URL, data)
      .pipe(
        catchError(error => {
          return throwError(error); // if you catch any errors, pass them (rethrow) to the error block
        })
       )
       .subscribe(
         result => {
           observer.next(result); // if you receive a result, pass to register function in register.page.ts
           observer.complete(); // close the observable
         },
         error => {
           observer.error(error); // if you receive an error, pass error to register function
           observer.complete(); // close the observable
          }
        );
      });
}

这篇关于如何保存服务器返回的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆