webpack dev server CORS issue

ghz 6months ago ⋅ 299 views

I am using webpack-dev-server v1.10.1 to boost up my Redux project and I have the options below:

contentBase: `http://${config.HOST}:${config.PORT}`,
quiet: false,
noInfo: true,
hot: true,
inline: true,
lazy: false,
publicPath: configWebpack.output.publicPath,
headers: {"Access-Control-Allow-Origin": "*"},
stats: {colors: true}

In the JS, I am using request from superagent to generate a HTTP GET call

request
          .get(config.APIHost + apiUrl)
          .set('Accept', 'application/json')
          .withCredentials()
          .end(function (err, res) {
                if (!err && res.body) {
                    disptach(() => {
                        return {
                            type: actionType || GET_DATA,
                            payload: {
                                response: res.body
                            }
                        }
                    });
                }
          });

But I got the CORS error:

XMLHttpRequest cannot load http://localhost:8000/api/getContentByType?category=all. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:5050' is therefore not allowed access

Any suggestion to resolve this? Thanks a lot

Answers

The CORS error you are encountering typically arises because the server at http://localhost:8000 is not set up to handle requests from a different origin, which in your case is http://localhost:5050. Even though you have specified Access-Control-Allow-Origin: * in your webpack dev server configuration, this only affects the files served by the webpack server and does not impact your API server running at http://localhost:8000.

To resolve this, you need to ensure that the API server at http://localhost:8000 includes the appropriate CORS headers in its responses.

Here's a general outline on how you can enable CORS on your API server, depending on the backend technology you are using:

For Express.js (Node.js)

If your API server is using Express.js, you can use the cors middleware to enable CORS:

  1. Install the CORS middleware:

    npm install cors
    
  2. Use the CORS middleware in your Express.js application:

    const express = require('express');
    const cors = require('cors');
    const app = express();
    
    app.use(cors());
    
    // Define your routes here
    app.get('/api/getContentByType', (req, res) => {
      // Your handler logic here
    });
    
    app.listen(8000, () => {
      console.log('API server running on http://localhost:8000');
    });
    

For Flask (Python)

If your API server is using Flask, you can use the flask-cors extension:

  1. Install the Flask-CORS extension:

    pip install flask-cors
    
  2. Use the Flask-CORS extension in your Flask application:

    from flask import Flask
    from flask_cors import CORS
    
    app = Flask(__name__)
    CORS(app)
    
    @app.route('/api/getContentByType', methods=['GET'])
    def get_content_by_type():
        # Your handler logic here
        return "Your response here"
    
    if __name__ == '__main__':
        app.run(port=8000)
    

For Django

If your API server is using Django, you can use the django-cors-headers package:

  1. Install the django-cors-headers package:

    pip install django-cors-headers
    
  2. Add it to your INSTALLED_APPS and configure it in your settings.py:

    # settings.py
    INSTALLED_APPS = [
        ...
        'corsheaders',
        ...
    ]
    
    MIDDLEWARE = [
        ...
        'corsheaders.middleware.CorsMiddleware',
        ...
    ]
    
    CORS_ORIGIN_ALLOW_ALL = True  # Or you can set specific allowed origins
    

Summary

Ensure that the API server (http://localhost:8000) includes the necessary CORS headers in its responses to allow requests from http://localhost:5050. This typically involves using a middleware or extension appropriate for your backend technology that automatically includes the Access-Control-Allow-Origin header in the server's responses.

If you cannot modify the API server and need a temporary workaround, you can use a proxy in your webpack dev server configuration to forward requests to the API server, which can help avoid CORS issues during development.

Example of using a proxy in webpack-dev-server

module.exports = {
  // Other webpack configuration settings...
  devServer: {
    contentBase: path.join(__dirname, 'public'),
    compress: true,
    port: 5050,
    proxy: {
      '/api': {
        target: 'http://localhost:8000',
        changeOrigin: true,
      },
    },
  },
};

With this proxy setup, requests to /api from the webpack dev server will be proxied to http://localhost:8000, thus avoiding CORS issues.