首页 > 解决方案 > 如何从 Angular 项目发送 NODE.JS 发布请求?

问题描述

我有一个使用 expressjs 连接到 SQL Server 的 NODE.JS api,我想在 Angular 项目中使用它。我使用两个文件,一个路由文件和一个控制器文件。我的路由文件如下:

module.exports = (app) => {
    const UsrContrllr = require('../Controllers/users.controllers');

    //1. GET ALL USERS
    app.get('/api/users', UsrContrllr.func1);

    
    //2. POST NEW USER
    app.post('/api/user/new', UsrContrllr.func2);
};

我的控制器文件如下:

const mssql = require('mssql');

exports.func1 = (req, res) => 
{
    // Validate request
    console.log(`Fetching RESPONSE`);
    // create Request object
    var request = new mssql.Request();
    // query to the database and get the records
    const queryStr = `SELECT * FROM USERS`;
    request.query(queryStr, function (err, recordset) {
        if (err) console.log(err)
        else {
            if (recordset.recordset.toString() === '') {
                res.send('Oops!!! Required data not found...');
            }
            else {
                // send records as a response
                res.send(recordset);
            }
        };
    });
};

exports.func2 = (req, res) =>
{
     // Validate request
     console.log(`INSERTING RECORD ${req}`);
     // create Request object
     var request = new mssql.Request();
     // query to the database and get the records
     const queryStr = `INSERT INTO GDUSERS (USERCODE, PASSWORD, LANGUAGE, USERCLASS, FIRSTNAME, LASTNAME, CONTACTNO) VALUES ('${req.body.usercode}', '${req.body.password}', 'EN', '0', '${req.body.firstname}', '${req.body.lastname}', '${req.body.contactno}');`;
     request.query(queryStr, function (err, recordset) {
         if (err) console.log(err)
         else {
             if (recordset.recordset.toString() == '') {
                 res.send('Oops!!! Required data not found...');
             }
             else {
                 // Send records as response
                 res.send(recordset);
             }
         };
    });
};

GET 请求运行良好,但是当我尝试直接从 Angular 应用程序运行 POST 请求时,我收到一条错误消息

无法获取 URL/api/user/new

我的角度项目中的角度代码是:

signup() {
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });

    console.log(this.user); //User details come from a form

    this.http.post(“URL", this.user, options)
    .subscribe( 
    (err) => {
        if(err) console.log(err);
        console.log("Success"); 
    });
  }

我不确定我使用的角度代码是否正确,我不知道我哪里出错了。如何从 Angular 项目中准确发送 http POST 请求?

标签: node.jsangularapipost

解决方案


这就是我通过 http.post 调用处理我的用户注册的方式。注册用户时,我的方法略有不同,因为我使用的是承诺而不是可观察的(我通常用于我的服务调用)。但我会告诉你两种方式。

createUser(user: User): Promise < string > {
  const promise = new Promise < string > ((resolve, reject) => {
   const userForPost = this.createUserForPost(user);
    this.http.post(environment.backendUrl + '/api/user/signup', userForPost, this.config).toPromise < HttpConfig > ()
    .then(createdUser => {
    }).catch(error => {
      console.log(error);
    });
});
 return promise; 
}

这是另一个带有可观察的示例

createForumPost(forumPost: ForumPost) {
 this.http.post < { message: string, forumPostId: string } > (environment.backendUrl + '/api/forumPosts', forumPost).subscribe((responseData) => {
  const id = responseData.forumPostId;
  forumPost.id = id;
 });
}

我在其他地方定义了我的 URL,然后只使用 environment.backedUrl + ' path ' 来定义我的路径(与后端控制器中的路径相同)

这是我在这里的第一个答案之一。如果它有点乱,我很抱歉,我希望我能帮助我的例子:)


推荐阅读