gpt4 book ai didi

通过 Angular 应用程序的 Node.js POST 请求返回错误 404 “not found"

转载 作者:行者123 更新时间:2023-12-04 09:30:42 29 4
gpt4 key购买 nike

我正在使用连接到 SQL Server 数据库的 Node.js 制作 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: falsestatus: 404statusText: "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 路由定义为/用户 /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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com