节点和Heroku,错误:请求的资源上不存在“Access-Control-Allow-Origin”标头

jqjz2hbq  于 2022-11-24  发布在  其他
关注(0)|答案(2)|浏览(159)

我知道这是一个常见的问题,有很多解决方案,但是我尝试了所有的方法,什么都没有改变。我在Heroku上部署了node和postgresql,以拥有一个Rest API,并通过HttpClient从Angular中获取它。我已经部署了它,在Postman中一切都正常,但是在浏览器中,它显示了这个错误:

CORS策略已阻止从源“http://localhost:4200”访问位于“https://myapi.herokuapp.com/products/”的XMLHttpRequest:请求的资源上不存在“Access-Control-Allow-Origin”标头。

这是我的节点应用程序:

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');
});

这是我的包裹

{
  "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项目部署在托管

krugob8w

krugob8w1#

我刚刚添加了一个包含以下内容的Procfile:'web:node src/index.js'.我希望它对你有用.

aor9mmx1

aor9mmx12#

感谢您的评论,我已经通过删除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/得到的

相关问题