Javascript 角度:http post请求-问题:";“未找到”;即使api端点已就位
我正在尝试做一个post请求,其中我在头中包含JWT令牌。我的问题是,在执行请求时,我得到一个错误:Javascript 角度:http post请求-问题:";“未找到”;即使api端点已就位,javascript,node.js,angular,web-development-server,Javascript,Node.js,Angular,Web Development Server,我正在尝试做一个post请求,其中我在头中包含JWT令牌。我的问题是,在执行请求时,我得到一个错误: ERROR HttpErrorResponse {headers: HttpHeaders, status: 404, statusText: "Not Found", url: "http://localhost:4200/api/asdf", ok: false, …} 我的请求如下所示: const httpOptions = { headers: new HttpH
ERROR HttpErrorResponse {headers: HttpHeaders, status: 404, statusText: "Not Found", url: "http://localhost:4200/api/asdf", ok: false, …}
我的请求如下所示:
const httpOptions = {
headers: new HttpHeaders({
'authorization': 'Bearer ' + localStorage.getItem('token')
})
};
await this.http.post<any>(
'/api/asdf',
httpOptions
)
.subscribe(data => {
this.usersFromBackEnd = data,
console.log(data)
});
我的handlers.index()方法是:
index (req, res) {
res.json({
success: true,
message: 'Index page'
});
}
let checkToken = (req, res, next) => {
let token = req.headers['x-access-token'] || req.headers['authorization']; // Express headers are auto converted to lowercase
if (token) {
if (token.startsWith('Bearer ')) {
// Remove Bearer from string
token = token.slice(7, token.length);
}
jwt.verify(token, config.secret, (err, decoded) => {
if (err) {
return res.json({
success: false,
message: 'Token is not valid'
});
} else {
req.decoded = decoded;
next();
}
});
} else {
return res.json({
success: false,
message: 'Auth token is not supplied'
});
}
我的中间件.checktoken()方法是:
index (req, res) {
res.json({
success: true,
message: 'Index page'
});
}
let checkToken = (req, res, next) => {
let token = req.headers['x-access-token'] || req.headers['authorization']; // Express headers are auto converted to lowercase
if (token) {
if (token.startsWith('Bearer ')) {
// Remove Bearer from string
token = token.slice(7, token.length);
}
jwt.verify(token, config.secret, (err, decoded) => {
if (err) {
return res.json({
success: false,
message: 'Token is not valid'
});
} else {
req.decoded = decoded;
next();
}
});
} else {
return res.json({
success: false,
message: 'Auth token is not supplied'
});
}
注意:url片段:/api/asdf
只是一个占位符,稍后将被替换
你能帮助我理解为什么会出现这个错误,以及如何解决它吗
提前非常感谢!
顺致敬意,
塞缪尔
编辑:错误消息包含localhost:4200,但是,我认为应该调用localhost:3000,因为在我的proxy.conf.json文件中是这样设置的:
{
"/api/*": {
"target": "http://localhost:3000",
"secure": false,
"logLevel": "debug",
"changeOrigin": true
}
}
此外,VSCode日志中的终端:
[HPM] POST /api/asdf -> http://localhost:3000
此外,我还以相同的方式对服务器端组件进行其他调用,在该组件中,我只指定代码段,而不指定localhost地址。如果我错了,请纠正我-我刚开始…您调用了错误的路由,您所说的路由没有在服务器上定义,这就是为什么它会给您404错误。您添加了“内容类型”吗?@Sam,您确定有正确的API url吗?在我看来,您正试图向客户端发送一个请求,因为事实显示url localhost:4200是Angular@mamosek的标准端口。我认为应该调用正确的地址-请参阅我问题的编辑。谢谢你帮助我@AbuSufian我尝试设置:```内容类型:``应用程序/json```但这并没有解决问题。。。