Sobatcoding.com - Enable CORS API di Node Express JS
Setelah kemaren sempet bahas cara enable CORS di Lumen Laravel, sekarang kita akan mencoba membuat CORS di REST API menggunakan Node Express JS. Berikut langkah-langkahnya.
Install package using npm
npm install cors
Contoh penggunaan cors untuk semua route.
const express = require("express");
const app = express();
var cors = require('cors');
const port = 8080;
app.use(express.json());
app.use(
express.urlencoded({
extended: true,
})
);
app.use(cors());
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});
Contoh penggunaan CORS untuk single route.
app.get('/articles', cors(), function (req, res, next) {
res.json({msg: 'This is CORS-enabled for a Single Route'})
})
Menambahkan whitelist domain tertentu.
const express = require("express");
const app = express();
var cors = require('cors');
const port = 8080;
app.use(express.json());
app.use(
express.urlencoded({
extended: true,
})
);
var allowlist = ['http://example1.com', 'http://example2.com']
var corsOptionsDelegate = function (req, callback) {
var corsOptions;
if (allowlist.indexOf(req.header('Origin')) !== -1) {
corsOptions = { origin: true } // reflect (enable) the requested origin in the CORS response
} else {
corsOptions = { origin: false } // disable CORS for this request
}
callback(null, corsOptions) // callback expects two parameters: error and options
}
app.use(cors(corsOptionsDelegate));
app.get("/", (req, res) => {
res.json({ message: "API Node JS" });
});
const appRoute = require('./config/routes');
app.use('/', appRoute);
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});
Untuk full source code bisa cek di akun github https://github.com/sobatcoding21/API-Node-JS
Sekian tutorial kali ini. Semoga bermanfaat.
Komentar 0