preveen-stack / nodejs

0 stars 0 forks source link

CORS Example with nodejs/express and python/flask #13

Open preveen-stack opened 1 month ago

preveen-stack commented 1 month ago

By default cross origin requests are disabled by single origin policy (SOP) We enable cross origin resource sharing on the server using express middleware

const express = require('express');
const app = express();

// Enable CORS middleware
app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*"); // Allow requests from any origin
  res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE"); // Allow specified HTTP methods
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); // Allow specified headers
  next();
});

// Define a route that will respond to GET requests
app.get('/data', (req, res) => {
  // This route just sends back a simple JSON response
  res.json({ message: 'Hello, CORS!' });
});

// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});
preveen-stack commented 1 month ago

Let's make a request to the server above and see the headers

curl -I http://127.0.0.1:3000/data
HTTP/1.1 200 OK
X-Powered-By: Express
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept
Content-Type: application/json; charset=utf-8
Content-Length: 26
ETag: W/"1a-QfrPoe8mVI9ttU6Nl+4EArfFxtk"
Date: Tue, 07 May 2024 05:17:58 GMT
Connection: keep-alive
Keep-Alive: timeout=5
preveen-stack commented 1 month ago

install flask-cors

pip install python-cors
from flask import Flask, jsonify
from flask_cors import CORS

app = Flask(__name__)
CORS(app)  # Enable CORS for all routes

# Define a route that will respond to GET requests
@app.route('/data')
def get_data():
    # This route just sends back a simple JSON response
    return jsonify({'message': 'Hello, CORS!'})

# Start the server
if __name__ == '__main__':
    app.run(debug=True)
preveen-stack commented 1 month ago
 curl -I http://127.0.0.1:5000/data
HTTP/1.1 200 OK
Server: Werkzeug/2.2.3 Python/3.11.8
Date: Tue, 07 May 2024 05:48:57 GMT
Content-Type: application/json
Content-Length: 32
Access-Control-Allow-Origin: *
Connection: close

server log

* Serving Flask app 'ex-python-cors'
 * Debug mode: on
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
 * Running on http://127.0.0.1:5000
Press CTRL+C to quit
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 977-055-346
127.0.0.1 - - [07/May/2024 11:18:57] "HEAD /data HTTP/1.1" 200 -