Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/api/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 用于使用不带CORS标头的API的网页包配置_Reactjs_Api_Webpack_Cors - Fatal编程技术网

Reactjs 用于使用不带CORS标头的API的网页包配置

Reactjs 用于使用不带CORS标头的API的网页包配置,reactjs,api,webpack,cors,Reactjs,Api,Webpack,Cors,我需要使用一个没有CORS头的公共API。我对网页很陌生,所以我通过阅读文章来采用这种方法。脚手架由公司提供。这是作业练习的第二部分 我已经找了好几个小时了,但似乎没有任何帮助。我总是得到相同的响应请求的资源上不存在“访问控制允许来源”标题… 这是我目前的webpack.config.js const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const HtmlWebpa

我需要使用一个没有CORS头的公共API。我对网页很陌生,所以我通过阅读文章来采用这种方法。脚手架由公司提供。这是作业练习的第二部分

我已经找了好几个小时了,但似乎没有任何帮助。我总是得到相同的响应
请求的资源上不存在“访问控制允许来源”标题…

这是我目前的
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>
    );
  }
}
从“React”导入React;
从“./index.jsx”导入房屋;
常量publicApi=”https://api.mcmakler.de/v1/advertisements";
导出默认类Dinamic扩展React.Component{
构造函数(){
超级();
此.state={
广告:[],
};
}
componentDidMount(){
获取(公共API)
。然后((结果)=>{
console.info('results:',results);
返回results.blob();
})
。然后((数据)=>{
console.info('数据:',数据);
const advisions=data.results.map((ad)=>{
返回(
{ad.title}

) }); this.setState({advisions}); }) .catch((错误)=>{ 控制台错误(“boom!:”,err); }) } render(){ 返回( 迪纳米克 {this.state.adverties} ); } }
我是错过了重要的事情还是完全错了


免责声明:这项工作是针对Web UI开发人员的,但我认为学习这项工作也很有趣

浏览器不允许从响应中读取禁止的标题,如“设置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('');
          }
        });
      },
    },
  },
}

不要尝试cors
fetch(url,{mode:'no cors'})
给我一个不透明的响应,没有用