【问题标题】:why cors policy error on ONLY ONE API endpoint为什么只有一个 API 端点上的 cors 策略错误
【发布时间】:2021-02-11 16:14:00
【问题描述】:

我有一个 MEAN 项目。

我添加了一个新的端点。并且仅针对该端点,我收到以下错误。所有其他路线都运行良好。

我无法弄清楚为什么只有一个 API 调用我会收到此错误。 请帮忙。

Access to XMLHttpRequest at 'http://localhost:3000/api/servlog/precheck' from origin
'http://localhost:4200' has been blocked by CORS policy: 
No 'Access-Control-Allow-Origin' header is present on the requested resource.

component.ts 方法

  preCheck(){
    this.isLoading = true;
    const stDate = new Date(this.form.value.stDate);
    this.adminService.preCheck(stDate)
      .subscribe(result => {
        this.preCheckDone = true;
        this.isLoading = false;
        if(result.logFound) {
          this.logFound = true;
        } else {
          this.logFound = false;
        }
      },
      err => {
        alert("An error occured while generating service log")
      });
  }

管理服务

  reqUrl: string = environment.apiUrl;

  preCheck(stDate: Date){
    return this.httpClient.post<{logFound: boolean}>(this.reqUrl + '/servlog/precheck', stDate);
  }

后端 app.js

const express = require('express');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const mongoose = require('mongoose');

....
const serviceLogRoutes = require('./routes/servicelog');
const errorHandler = require('./middleware/error-handler');

const app = express();   //creating an express app

mongoose.connect('xxxxxxxxxxxx', { useFindAndModify: false }  )
  .then(() => {
    console.log('Connected to database.');
  })
  .catch(() => {
    console.log('Database connection failed.');
  });

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());

app.use((req, res, next) => {
  res.setHeader('Access-Control-Allow-Origin', 'http://localhost:4200');
  res.setHeader("Access-Control-Allow-Credentials", true);
  res.setHeader(
    'Access-Control-Allow-Headers',
    'Origin, X-Requested-With, Content-Type, Accept, Authorization, x-client-key, x-client-token, x-client-secret');

  res.setHeader(
    'Access-Control-Allow-Methods',
    'GET, POST, PUT, PATCH, DELETE, OPTIONS')

  if (req.method === 'OPTIONS') {
    return res.status(200).end();
  }

  next();
 });

....
app.use('/api/services', serviceRoutes);
app.use('/api/servlog', serviceLogRoutes);

app.use(errorHandler);

module.exports = app;

后端路由

const express = require('express');
const router = express.Router();

const servLogCtlr = require('../controllers/servicelog');

router.post('createlog', servLogCtlr.createServiceLog);
router.post('precheck', servLogCtlr.preCheck);

module.exports = router;

后端控制器方法

exports.preCheck = (req, res, next) => {
  console.log(req.body);
  const stDate = new Date(req.body);
  let FY;
  if(stDate.getMonth() === 0 && stDate.getDate() === 1 ){
    FY = stYear;
  } else {
    FY = stYear + '-' + String(stYear + 1).match(/\d{2}$/);
  }

  ServiceLog
    .findOne({ FY: FY })
    .then(log => {
      if(log){
        res.status(200).json({logFound: true});
      } else {
        res.status(200).json({logFound: false});
      }
    })
    .catch(next)
}

【问题讨论】:

  • 那么,问题出在哪里?

标签: cors mean-stack


【解决方案1】:

cors 错误已解决。

这是由于在 adminService Http 调用中传递有效负载(日期值)的方式。

错误:将 stDate 作为 stDate 传递

更正:在 http post 调用中将 stDate 作为 {stDate} 传递。

preCheck(stDate: Date){
    return this.httpClient.post<{logFound: boolean}>(this.reqUrl + '/servlog/precheck', {stDate});
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-31
    • 1970-01-01
    • 2020-05-02
    • 2022-01-26
    • 2023-03-13
    • 2021-07-31
    • 2013-11-28
    • 1970-01-01
    相关资源
    最近更新 更多