我正在使用 Node.js 制作一个连接到 SQL Server 数据库的 API。我的 GET 请求运行良好,但我的 POST 请求出现错误。我已将 Node 项目分为两个文件,一个路由文件和一个 Controller 文件。
我的路由文件中的代码如下:
module.exports = (app) => {
const UsrContrllr = require('../Controllers/users.controllers');
//1. GET ALL USERS
app.get('/api/users', UsrContrllr.getAllUsers);
//2. POST NEW USER
app.post('/api/user/new', UsrContrllr.addNewUser);
};
我的 Controller 文件中的代码如下:
const mssql = require('mssql');
exports.getAllUsers = (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.addNewUser = (req, res) =>
{
// Validate request
console.log(`INSERTING RECORD ${req.body}`);
// create Request object
var request = new mssql.Request();
// query to the database and get the records
const queryStr = `INSERT INTO USERS (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}');`;
console.log(queryStr);
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);
}
};
});
};
当我从 Angular 应用程序运行 POST 请求时,我收到 HttpErrorResponse,错误 404 未找到。
error: “Error: Cannot POST /api/users/new" message: "Http failure response for http://url:port/api/users/new: 404 Not Found" name: "HttpErrorResponse" ok: false status: 404 statusText: "Not Found” url: "http://url:port/api/users/new”
服务文件中的 Angular 代码如下:
private url = 'http://url:port/api/users';
signup(fName: string, lName: string, usrCode: string, pwd: string, cntctNbr: string) {
const headers = new HttpHeaders().set('Content-Type', 'application/json');
const newUsr = {
usercode: usrCode,
password: pwd,
firstname: fName,
lastname: lName,
contactno: cntctNbr
}
this.http.post(this.url + '/new', JSON.stringify(newUsr), { headers: headers }).subscribe(data => {
console.log(data);
});
}
我不明白为什么我无法添加新用户。有人告诉我我的代码看起来不错,但我没有看到任何结果。我哪里出错了?
最佳答案
您收到 404(未找到)错误,因为您的 POST 路由被定义为/user/new 但在您的 Angular 应用程序中您正在调用 http://url:port/api/<强>用户/新
将 API 中的代码更正为以下内容:
app.post('/api/users/new', UsrContrllr.addNewUser);
关于通过 Angular 应用程序的 Node.js POST 请求返回错误 404 “not found",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62866894/