如何从Angular项目发送NODE.JS发布请求?

时间:2020-07-09 22:36:06

标签: node.js angular api post

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

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请求运行良好,但是当我尝试直接从角度应用程序运行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请求?

1 个答案:

答案 0 :(得分:1)

这是我通过http.post调用处理用户注册的方式。在注册用户时,我的方法略有不同,因为我使用的是promise而不是observable(通常用于服务呼叫)。但我会向你展示两种方式。

i_sqrt dq 0

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

idiv qword [i_sqrt]

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

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