【问题标题】:GET http://localhost:4000/api/admin/view 400 (Bad Request)GET http://localhost:4000/api/admin/view 400(错误请求)
【发布时间】:2019-11-01 18:06:55
【问题描述】:

我需要 MEAN 堆栈方面的帮助。每当我的浏览器加载时显示错误“GET http://localhost:4000/api/admin/view400 (Bad Request)”但是当我打邮递员时它工作正常。不明白我缺少什么

Component Ts

})
export class ViewAllComponent implements OnInit {
  users: any = [];
  //searchUser;

  constructor(private adminServiceService: AdminServiceService) { }

  ngOnInit() {
    this.adminServiceService.getUsers()
    .subscribe((data: any) => {
      console.log(data.data);

      this.users = data.data;
      console.log(this.users);
    });
  }

}

Component Html

<div class="container">
  <div class="row">
<!-- <div class="search-user" style="margin:5px;">
<input class="form-control" type="text" name="search" [(ngModel)]="searchUser" autocomplete="off" placeholder="Search By Name">
</div> -->
<div>
  <a [routerLink]="['/register']" class="btn btn-primary" style="margin:5px;">Add New User</a>
</div>

<table class="table table-striped" >
  <thead>
  <tr>
      <td>User Name</td>
      <td>User Email</td>
      <td>User Phone</td>
      <td colspan="2">Actions</td>
  </tr>
  </thead>
<tbody>
    <tr *ngFor="let user of users">
        <td>{{ user.UserName }}</td>
        <td>{{ user.UserEmail }}</td>
        <td>{{ user.userPhone }}</td>

        <td><a href="#" class="fa fa-edit"></a></td>
        <td><a href= "#" class="fa fa-trash"></a>
        <td><a href="#" class="fa fa-eye"></a></td>

        <!-- <td><button type="button" class="btn btn-xs " (click)="approvalPendingRequest(user._id)">
  <i [ngClass]="['fa', user.IsActive ? 'fa-lock' : 'fa-unlock']" aria-hidden="true"></!-->
      <!-- </button> -->
        <!-- </td> -->

    </tr>
</tbody>
</table>
</div>
</div>

adminservice.ts

import { map } from "rxjs/operators";
import { HttpClient, HttpClientModule } from "@angular/common/http";
import { Injectable } from "@angular/core";

@Injectable({
  providedIn: "root"
})
export class AdminServiceService {
  uri = "http://localhost:4000/api/admin";

  constructor(private http: HttpClient) {}

  // save Admin in Databse
  addAdmin(value) {
    return this.http.post(`${this.uri}/add`, value);
  }

  getUsers() {
    return this.http.get(`${this.uri}/view`);
    // .pipe(map((res: Response) => res.json()));
  }
}

Server.js

const express = require("express");
const bodyParser = require("body-parser");
const path = require("path");
const cors = require("cors");
const mongoose = require("mongoose");
const nodemailer = require("nodemailer");
const flash = require("express-flash-messages");
const routers = require("./Router/Router");
const config = require("./DB");
mongoose.Promise = global.Promise;
mongoose.connect(config.DB, { useNewUrlParser: true }).then(
  () => {
    console.log("Database Connected");
  },
  err => {
    console.log("Database is not connected");
  }
);
const app = express();
app.use(flash());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept"
  );
  next();
});
app.use("/api", routers);
let port = process.env.PORT || 4000;
app.listen(port, () => {
  console.log("Listing On Port", +port);
});

Controllers.js

const User = require('../Models/User');

exports.allUser = function(req, res){
  User.find({}, function (err, user){
    if (err){
      res.status(400).json({status:false, 'err':err})
    }
    else{
      res.status(400).json({status:true, 'data': user})
    }
  })

}

Router

// Get All Users
router.get('/admin/view', viewAllUsersCtrl.allUser)

当我尝试使用 http.get 运行代码时,它返回 400 错误请求。我尝试多次更改 http 标头内容类型,但没有成功,以及许多其他无果的解决方案尝试。请帮帮我:(

谢谢!

【问题讨论】:

  • 你能检查开发者控制台吗?您的问题可能与 cors 有关
  • 我认为问题出在 API 方面。据我所知,您发布的代码看起来还不错...
  • 只是做:app.use((req,res,next)=&gt; { res.header('Access-Control-Allow-Origin': '&lt;your-frontend-server-url:port'); next();});,这是 cors 问题,邮递员不是浏览器,这就是为什么发出该请求没有问题,但浏览器具有某些安全方面,如跨域、同源维护安全的东西
  • 我把所有的代码都贴出来了。
  • 启用 cors 或使用代理:)

标签: node.js angular mongodb


【解决方案1】:

在 Postman 工作时,您似乎有一个 CORS,但是 AJAX 请求不起作用。需要做的是to allow CORS in Node.js:

$ npm install cors

然后启用所有 CORS 请求:

var express = require('express')
var cors = require('cors')
var app = express()

app.use(cors())

app.get('/products/:id', function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for all origins!'})
})

app.listen(80, function () {
  console.log('CORS-enabled web server listening on port 80')
})

更新:

试试这个方法:

var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);

io.set('origins', '*:*');

app.use(function(req, res, next) {
  res.header('Access-Control-Allow-Origin', req.get('Origin') || '*');
  res.header('Access-Control-Allow-Credentials', 'true');
  res.header('Access-Control-Allow-Methods', 'GET,HEAD,PUT,PATCH,POST,DELETE');
  res.header('Access-Control-Expose-Headers', 'Content-Length');
  res.header('Access-Control-Allow-Headers', 'Accept, Authorization, Content-Type, X-Requested-With, Range');
  if (req.method === 'OPTIONS') {
    return res.send(200);
  } else {
    return next();
  }
});

server.listen(80);

app.get('/', function (req, res) {
  res.send('OK');
});

io.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});

【讨论】:

  • @DheerajKumar 你用过上面的代码吗?浏览器的控制台说什么?
  • 感谢大家的支持。我解决了错误
  • @DheerajKumar 很高兴您解决了问题。 What should I do when someone answers
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-05-19
  • 1970-01-01
  • 1970-01-01
  • 2022-01-21
  • 1970-01-01
  • 1970-01-01
  • 2014-08-18
相关资源
最近更新 更多