У меня проблема с моим API node.js. У меня есть API, работающий на порту 3000, и угловой интерфейс с портом 4200.
Когда я отправляю запрос из angular в API, у меня возникает ошибка CORS. Я пробовал три разных решения, но все еще не работал.
app.use(cors());
app.use((req, res, next) => { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"); next(); })
app.use(cors({ origin: 'http://frontend.com:4200' }));
Ничего из вышеперечисленного не сработало, т.е. я все еще постоянно получаю ошибку с CORS. Когда я отправляю запрос от Postman, все работает нормально.
Мой фактический код:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const carRoutes = require('./routes/car');
const sequelize = require('./util/db');
const cors = require('cors');
sequelize.sync().catch(error => {
console.info(error);
});
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(cors());
app.use(carRoutes);
app.listen(3001);
Сообщение об ошибке:
A request to a resource of another origin has been blocked: the "Same Origin Policy" policy does not allow remote resources to be loaded from "http://localhost:3000/car" (failed CORS request).
@Jota.Toledo Я добавляю сообщение об ошибке в свой пост
Это как-то связано с тем, что в вашем примере ваш внутренний сервер прослушивает 3001, но вы используете 3000?
А вы пробовали app.use(cors({ origin: true }))?





Более простое решение — реализовать прокси, который будет перенаправлять ваш вызов API на localhost:300.
Добавьте новый файл с именем proxy.config.json и добавьте в него следующую конфигурацию json.
{
"/car/*": {
"target": "http://localhost:3000",
"secure": false,
"logLevel": "debug"
}
}
после этого вам нужно обновить свой package.json раздел Scripts, указав следующий код: "start": "ng serve --proxy-config proxy.config.json",. Делайте все вышеперечисленное при использовании npm start, в противном случае вы можете просто запустить ng serve --proxy-config proxy.config.json в командной строке, не обновляя свой package.json, но вам придется не забывать запускать его каждый раз.
Иногда CORS — это больше, чем просто Access-Control-Allow-Origin. Попробуйте следующее:
// Set up CORS
app.use(cors({
origin: true, // "true" will copy the domain of the request back
// to the reply. If you need more control than this
// use a function.
credentials: true, // This MUST be "true" if your endpoint is
// authenticated via either a session cookie
// or Authorization header. Otherwise the
// browser will block the response.
methods: 'POST,GET,PUT,OPTIONS,DELETE' // Make sure you're not blocking
// pre-flight OPTIONS requests
}));
Вы также можете поэкспериментировать с allowedHeaders, exposedHeaders и т. д. Установка maxAge уменьшит количество запросов перед полетом — на самом деле это не решит проблемы с cors, но уменьшит сетевой трафик.
Note on
origin: true. If your endpoint requires credentials then the browser will not respect the*pattern. The Access-Control-Allow-Origin header must match the url of the request (including weather it's http or https). Fortunately thecorsmiddleware will do this automatically for you if you setorigintotrue
какую ошибку вы получаете?