You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 12调用登录API返回401 Unauthorized,Postman可正常请求

Angular 12调用登录API返回401 Unauthorized,但Postman可正常请求的问题排查

问题说明

  • 通过Chrome浏览器的HTML表单调用登录API时,收到http://localhost:3000/test的401 Unauthorized响应
  • 目标登录API地址为http://localhost:3000/witslogin,该接口在Postman中可正常返回成功响应,但Angular 12调用时失败

Postman成功响应示例

{
"msg": "Logged in!",
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MTIsImlhdCI6MTY3MTI4MjkxMywiZXhwIjoxNjcxMjg2NTEzfQ.Q7Gnxia3SvnD_v5B4D_7xblKh1y4j6NlQONNWmzyx8U",
"witsusers": {
"id": 12,
"fullname": "Test User",
"email": "test@test.com",
"password": "$2a$10$6qcx7ZgYe662jI70tz4ejegbgnhdoNJYYALVo059WaQF2e1NCAjny",
"last_login": "2022-12-17T12:56:51.000Z"
}
}

相关代码

Angular 12登录代码

login(email: string, password: string) {
    const loginData: LoginData = {email:email, password:password}
    this.http.post<{token: string, expiresIn: number }>("http://localhost:3000/witslogin", loginData)
    .subscribe(response => {
      console.log(response);
    })
}

Node.js后端登录接口代码

const witsLogin = async (req, res, next) => {
    console.log("Users Login API is working");
    db.query(
        `SELECT * FROM witsusers WHERE email = ${db.escape(req.body.email)};`,
        (err, result) => {
          // 用户不存在
          if (err) {
            throw err;
          }
          if (!result.length) {
            return res.status(401).send({
              msg: 'Email or password is incorrect!'
            });
          }
          // 校验密码
          bcrypt.compare(
            req.body.password,
            result[0]['password'],
            (err, bResult) => {
              // 密码错误
              if (err) {
                throw err;
              }
              if (bResult) {
                const token = jwt.sign({id:result[0].id},'the-super-strong-secrect',{ expiresIn: '1h' });
                db.query(
                  `UPDATE witsusers SET last_login = now() WHERE id = '${result[0].id}'`
                );
                return res.status(200).send({
                  msg: 'Logged in!',
                  token,
                  witsusers: result[0]
                })
              }
              return res.status(401).send({
                msg: 'Username or password is incorrect!'
              });
            }
          );
        }
      );
}

排查及解决方法

  1. 跨域(CORS)限制
    Postman不受浏览器CORS规则约束,但Angular前端在浏览器中请求时会触发。需在Node.js后端配置CORS中间件,允许前端域名的请求:

    const cors = require('cors');
    app.use(cors({ origin: 'http://localhost:4200' })); // 替换为你的Angular项目端口
    
  2. 请求内容类型不匹配
    确保Angular发送的请求格式为JSON,后端能正确解析。可在Angular中显式设置请求头:

    import { HttpHeaders } from '@angular/common/http';
    
    const headers = new HttpHeaders({ 'Content-Type': 'application/json' });
    this.http.post<{token: string, expiresIn: number }>("http://localhost:3000/witslogin", loginData, { headers })
    

    同时后端需启用JSON解析中间件:

    app.use(express.json());
    
  3. 请求路径异常
    错误提示指向/test,但Angular调用的是/witslogin,需检查:

    • Angular是否存在HTTP拦截器修改了请求路径
    • 后端路由是否存在重定向规则,将/witslogin导向/test
  4. 参数传递错误
    在Angular的login方法中添加console.log(loginData),确认发送的邮箱、密码与Postman中一致,排查表单输入值是否正确传递到API调用中。

  5. 后端SQL查询问题
    在Node.js接口中打印req.body.email,确认接收到的邮箱与Postman发送的一致;检查db.escape是否正确转义了特殊字符,避免查询逻辑出错导致用户匹配失败。

内容的提问来源于stack exchange,提问作者Shahnawaz Alam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 11:25:16