Webpack配置使用没有CORS头的API

时间:2018-03-01 23:02:51

标签: reactjs api webpack cors

我需要使用没有CORS头的公共API。我是webpack的新手,所以我通过readind文章采用这种方法。脚手架由公司提供。这是工作练习的第二部分。

我一直在寻找好几个小时,似乎没有任何帮助。我总是得到相同的回复No 'Access-Control-Allow-Origin' header is present on the requested resource ...

此时此webpack.config.js

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

const HtmlWebpackPluginConfig = new HtmlWebpackPlugin({
  template: './client/index.html',
  filename: 'index.html',
  inject: 'body'
})
module.exports = {
  entry: './client/index.js',
  output: {
    path: path.resolve('dist'),
    filename: 'index_bundle.js'
  },
  module: {
    rules: [
      { test: /\.js$/,
        exclude: /node_modules/,
        use: ['babel-loader'],
      },
      { test: /\.jsx$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
      },
      {
        test: /\.(sass)$/,
        use: [{
            loader: "style-loader"
          }, {
            loader: "css-loader"
          }, {
            loader: "sass-loader"
        }]
      },
      {
        test: /\.html/,
        loader: 'raw-loader'
      },
    ],
  },
  plugins: [HtmlWebpackPluginConfig],
  devServer: {
    contentBase: './src/public',
    port: 1184,
    proxy: {
      'https://api.mcmakler.de/v1/advertisements': {
        target: 'https://api.mcmakler.de/v1/advertisements',
        secure: false
      }
    }
  },
  resolve: {
    extensions: [ '.js', '.jsx' ]
  }
};

我的家属是:

 "devDependencies": {
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.2",
    "babel-preset-env": "^1.6.1",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "css-loader": "^0.28.9",
    "eslint": "^4.0.0",
    "file-loader": "^1.1.8",
    "html-webpack-plugin": "^2.28.0",
    "node-sass": "^4.7.2",
    "raw-loader": "^0.5.1",
    "sass-loader": "^6.0.6",
    "style-loader": "^0.20.2",
    "url-loader": "^0.6.2",
    "webpack": "^2.6.1",
    "webpack-dev-server": "^2.4.5"
  },
  "dependencies": {
    "react": "^16.2.0",
    "react-dom": "^16.2.0",
    "yarn": "^1.3.2"
  }

这是我的jsx文件,它是一个呈现广告的简单组件

import React from 'react';

import House from './index.jsx';

const publicApi = "https://api.mcmakler.de/v1/advertisements";

export default class Dinamic extends React.Component {
    constructor () {
        super();
        this.state = {
            advertisements: [],
        };
    }
    componentDidMount() {

        fetch(publicApi)
        .then((results) => {
                console.info('results: ', results);
                return results.blob();
            })
            .then ((data) => {
                console.info('data: ', data);
                const advertisements = data.results.map((ad) => {
                    return (
                        <div key="ads.results" >
                            <p>{ad.title}</p>
                        </div>
                    )
                });
                this.setState({ advertisements });
            })
            .catch((err) => {
                console.error("boom!: ", err);
            })
    }
  render() {
    return (
      <div className="container-fluid">
        <div className="container">
            <h1>Dinamic</h1>
          <div className="row">
                        {this.state.advertisements}
          </div>
        </div>
      </div>
    );
  }
}

我是否错过了一些重要的内容,或者这是完全错误的?

免责声明:这项工作适用于Web UI开发人员,但我认为这也很有趣

1 个答案:

答案 0 :(得分:2)

浏览器不允许从响应中读取禁止标题,例如'set-cookie',浏览器也不允许设置'Cookie'标题。所以我通过在onProxyRes方法中读取cookie并将其保存在变量中并在onProxyReq方法中按照以下请求设置保存的cookie来解决了这个问题。

let cookie;
devConfig.devServer = {  
  proxy: {
    '*': {
      target: https://target.com,
      secure: false, 
      changeOrigin: true, 
      onProxyReq: (proxyReq) => {
        proxyReq.setHeader('Cookie', cookie);
      },
      onProxyRes: (proxyRes) => {
        Object.keys(proxyRes.headers).forEach((key) => {
          if (key === 'set-cookie' && proxyRes.headers[key]) {
            const cookieTokens = split(proxyRes.headers[key], ',');
            cookie = cookieTokens.filter(element => element.includes('JSESSIONID')).join('');
          }
        });
      },
    },
  },
}