To enable CORS (Cross-Origin Resource Sharing) in your Express.js application, you will need to set the necessary HTTP headers. One way to do this for every route in your API is to use the cors middleware from npm.
Here's how you can do that:
- First, you need to install the
cors package if you haven't already done so. You can do this from your command line terminal by running the following command:
npm install cors --save
- Once you've installed the
cors package, you need to require it in your configuration file and use it as middleware for your Express application:
const express = require('express');
const app = express();
const cors = require('cors'); // Require the cors library
const PORT = 8080;
// Enable CORS for all routes
app.use(cors());
// ... rest of your code
The default settings for the cors() middleware will allow access to your API from any origin. If you need to configure more specific options, you can do so by passing an options object to the cors() middleware. Here's an example where we allow only a specific origin and specific headers:
// Set up CORS options
const corsOptions = {
origin: 'http://example.com', // Replace with the URL of your front-end app
optionsSuccessStatus: 200,
methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
allowedHeaders: "Content-Type,Authorization"
};
app.use(cors(corsOptions));
// ... rest of your code
Here's how the full API file would look with CORS enabled, using the default settings:
const express = require('express');
const app = express();
const cors = require('cors');
const mysql = require('mysql');
const PORT = 8080;
app.use(cors()); // Use the cors middleware
// Connect to SQL
const db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'TransitU',
});
db.connect(err => {
if(err) { throw err; }
console.log("Connected to MySQL");
});
// ... the rest of your code (including route definitions) ...
app.listen(
PORT,
() => console.log(`API running on ${PORT}`)
);
By adding app.use(cors()); before your routes, CORS will be enabled for all routes in your application, allowing for cross-origin requests. If you need to activate CORS for specific routes, you can use cors() as route middleware:
const express = require('express');
const app = express();
const cors = require('cors');
const PORT = 8080;
// Enable CORS only for specific routes
app.get('/classes/:id', cors(), (req, res) => {
// Your route logic...
});
// ... rest of your routes and code ...
app.listen(
PORT,
() => console.log(`API running on ${PORT}`)
);
If you use CORS as route middleware, you can set different CORS policies for each route or group of routes. Make sure to include the CORS middleware before any other route-specific logic or middleware to ensure the headers are set appropriately.