Node and Heroku, error: No 'Access-Control-Allow-Origin' header is present on the requested resource

Node and Heroku, error: No 'Access-Control-Allow-Origin' header is present on the requested resource

我知道这是一个常见问题,有很多解决方案,但我尝试了所有方法,但没有任何改变。 我在 Heroku 上部署了节点和 postgresql 以获得 Rest API 并使用 HttpClient 从 Angular 获取它。我已经部署了它并且在 Postman 中一切正常,但是在浏览器中,它显示了这个错误:

从来源 'http://localhost:4200' 到 'https://myapi.herokuapp.com/products/' 处的 XMLHttpRequest 的访问已被 CORS 策略阻止:所请求的资源上不存在 'Access-Control-Allow-Origin' header .

这是我的节点应用程序:

const express = require('express');
const cors = require('cors');
const app = express();

//MiddleWares
app.use(express.json());
app.use(express.urlencoded({extended:false}));

//Router:
app.use(require('./routes/index'));

const PORT = process.env.PORT || 4000;

const corsOptions = {origin: process.env.URL || '*', credentials: true};

app.use(cors(corsOptions));

app.use((req, res, next) => {
    res.header("Access-Control-Allow-Origin", "*")
    res.header(
      "Access-Control-Allow-Headers",
      "Origin, X-Requested, Content-Type, Accept Authorization"
    )
    if (req.method === "OPTIONS") {
      res.header(
        "Access-Control-Allow-Methods",
        "POST, PUT, PATCH, GET, DELETE"
      )
      return res.status(200).json({})
    }
    next()
  });

app.listen(PORT, err => {
    if(err) throw err;
    console.log('Server on port 4000');
});

这是我的 package.json:

{
  "name": "backend",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "node src/index.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "cors": "^2.8.5",
    "express": "^4.18.1",
    "pg": "^8.7.3"
  },
  "devDependencies": {
    "nodemon": "^2.0.16"
  }
}

和Angular:

  constructor(
    private http: HttpClient
  ) { }

  getAllProducts() {
    return this.http.get<Product[]>(`${environment.url_api}/products/`);
  }

浏览器扩展没有帮助,因为我需要在主机上部署 Angular 项目

感谢您的评论,我已经通过删除 cors 包并只有一堆用于 cors 配置的代码来解决它。我的节点应用程序在此结束:

const express = require('express');
const app = express();


//Cors Configuration - Start
app.use((req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*")
  res.header(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested, Content-Type, Accept Authorization"
  )
  if (req.method === "OPTIONS") {
    res.header(
      "Access-Control-Allow-Methods",
      "POST, PUT, PATCH, GET, DELETE"
    )
    return res.status(200).json({})
  }
  next()
})
//Cors Configuration - End


//Router:
app.use(require('./routes/index'));

const PORT = process.env.PORT || 4000;

app.listen(PORT, err => {
    if(err) throw err;
    console.log('Server on port 4000');
});

如您所见,我没有使用 cors npm 包。 : 我从这个博客 https://medium.com/nerd-for-tech/solving-cors-errors-associated-with-deploying-a-node-js-postgresql-api-to-heroku-1afd94964676/