我知道這是一個常見問題,并且有很多解決方案,但是我嘗試了一切,但沒有任何改變。我在 Heroku 上部署了 node 和 postgresql 以擁有一個 Rest API 并使用 HttpClient 從 Angular 獲取它。我已經部署了它,并且 Postman 一切正常,但是在瀏覽器中,它向我顯示了這個錯誤:
從源“http://localhost:4200”訪問“https://myapi.herokuapp.com/products/”處的 XMLHttpRequest 已被 CORS 策略阻止:不存在“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');
});
這是我的 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"
}
}
和角:
constructor(
private http: HttpClient
) { }
getAllProducts() {
return this.http.get<Product[]>(`${environment.url_api}/products/`);
}
瀏覽器擴展無濟于事,因為我需要在主機上部署 Angular 專案
uj5u.com熱心網友回復:
感謝您的評論,我已經通過洗掉 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/
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/472681.html
標籤:节点.js 有角度的 PostgreSQL heroku 科尔斯
