简体   繁体   中英

Fetch,axios not woking in Reactjs

Here is my code and my only problem in fetch and axios are not working.Do i need to add some plugins for promise or fetch inmy webpack.config.js to achieve so?If i use cdn for fetch then it works fine.Please guide how to implement it in webpack

    var React=require('react');
var ReactDOM=require('react-dom');
var fetch=require('fetch');
var Header = React.createClass({
      getOccasion: function(evt) {
          alert(evt.target.value)
            fetch('/holidays/occasion', {
              credentials: 'same-origin',
              method: 'POST',
              headers: {
                'Content-Type': 'application/json'
              },
              body: JSON.stringify({
               state: evt.target.value,
             })
            });
          },
  render: function() {
var state=this.props.holidays.state;
var ButtonGroup = ReactBootstrap.ButtonGroup,
Button  = ReactBootstrap.Button;
    return (
      <div>
      <ButtonGroup>
      <Button bsStyle="danger">Danger!</Button>
  </ButtonGroup>

      <select onChange={this.getOccasion}>
      <option value="states">States</option>
      {
          this.props.holidays.map(function(holidays,i) {
          return <option key={i}
            value={holidays.state}>{holidays.state}</option>;
        })
      }
    </select>




      </div>
    );
  }
});

Update:App.js

    var React=require('react');
var ReactDOM=require('react-dom');
var Pusher=require('pusher-js');
var fetch = require('node-fetch');

var Header=require('./components/header.js');
var App = React.createClass({
  getInitialState: function() {
    return { items: [], holidays: [] };
  },

  componentWillMount: function() {
      alert("in mount")

    this.pusher = new Pusher("ba34e3874d4b87905f36", {
      encrypted: true,
      cluster: 'ap2',
    });
    this.channel = this.pusher.subscribe("doodles");
    this.total = 0;
    alert("in pusher")
  },

  componentDidMount: function() {
      alert("in did")


   fetch('/holidays',{credentials: 'same-origin',}).then(function(response) {
        return response.json();
    }).then(this.getHolidaysSuccess);

  },
  componentWillUnmount: function() {
    // Unbind from channel events
    this.channel.unbind();

    // Unsubscribe from the Pusher channel
    this.pusher.unsubscribe(this.channel);

    // Unregister by assign them to an empty function
    this.getHolidaysSuccess = function() {};

  },


  getHolidaysSuccess: function(response) {

       alert(JSON.stringify(response))

    this.setState({
        holidays: response
    });
  },


  render: function() {
      alert("in render1")

    return (
      <div>

<Header holidays={this.state.holidays} />

      </div>
    );
  }
});

ReactDOM.render(<App />, document.getElementById("app"));

my webpack.config.js

var webpack = require('webpack');
module.exports = {
  entry: './src/main/resources/static/js/app.js',
  output: {
    path: __dirname + '/src/main/resources/static/js', 
    filename: 'bundle.js' 
  },


  module: {

    loaders: [
      {
          test: /\.jsx?$/,
          exclude: /node_modules/,
          loader: 'babel-loader',
        query: {
          presets: ['es2015', 'react']
        }
      } ]
  },

      plugins: [  
                new webpack.ProvidePlugin({
                      Promise: 'imports-loader?this=>global!exports-loader?global.Promise!es6-promise',
                      fetch: 'imports-loader?this=>global!exports-loader?global.fetch!whatwg-fetch'
                 })
            ]
};

You need to install and import fetch from node-fetch instead of fetch like

 npm install -S node-fetch

and then import like

var fetch = require('node-fetch');

DOC

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM