如何在asp.net核心之上的Reactjs中设置路由

时间:2018-11-17 10:09:58

标签: reactjs asp.net-core single-page-application

我是reactjs的新手。我使用webpack手动配置了Reactjs,并将其添加到Asp.net Core项目中。 我想使用Web Api控制器,但是在React中,使用PlantInfo Component提取数据时收到404错误消息。在浏览器中刷新子页面时,也会出现空白屏幕。

PlantInfo控制器

namespace PLIMO.Web_R.Areas.General.Controllers
{
    [Area("General")]
    [Route("api/[controller]")]
    [ApiController]
    public class PlantInfoController : ControllerBase
    {
        private static string[] Summaries = new[]
   {
   "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm",
   "Balmy", "Hot", "Sweltering", "Scorching"
  };
        [HttpGet("[action]")]
        public IEnumerable<WeatherForecast> WeatherForecasts()
        {
            var rng = new Random();
            return Enumerable.Range(1, 5)
            .Select(index => new WeatherForecast
            {
                DateFormatted = DateTime.Now.AddDays(index).ToString("d"),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            });
        }
        public class WeatherForecast
        {
            public string DateFormatted { get; set; }
            public int TemperatureC { get; set; }
            public string Summary { get; set; }
            public int TemperatureF
            {
                get
                {
                    return 32 + (int)(TemperatureC / 0.5556);
                }
            }
        }
    }
}

PlantInfo Reactjs组件

import React, {Component} from 'react';
import 'es6-promise';
import 'isomorphic-fetch';

export default class PlantInfo extends Component {
    constructor() {
        super();
        this.state = { forecasts: [], loading: true };
        fetch('api/General/PlantInfo/WeatherForecasts')
            .then(response => response.json())
            .then(data => {
                this.setState({ forecasts: data, loading: false });
            });
    }
    render() {
        let contents = this.state.loading ? <p><em>Loading...</em></p>
            : PlantInfo.renderForecastsTable(this.state.forecasts);

        return <div>
            <h1>Weather forecast</h1>
            <button onClick={() => { this.refreshData() }}>Refresh</button>
            <p>This component demonstrates fetching data from the server.</p>
            {contents}
        </div>;
    }
    refreshData() {
        fetch('api/General/PlantInfo/WeatherForecasts')
            .then(response => response.json())
            .then(data => {
                this.setState({ forecasts: data, loading: false });
            });
    }
    static renderForecastsTable(forecasts) {
        return <table className='table'>
            <thead>
                <tr>
                    <th>Date</th>
                    <th>Temp. (C)</th>
                    <th>Temp. (F)</th>
                    <th>Summary</th>
                </tr>
            </thead>
            <tbody>
                {forecasts.map(forecast =>
                    <tr key={forecast.dateFormatted}>
                        <td>{forecast.dateFormatted}</td>
                        <td>{forecast.temperatureC}</td>
                        <td>{forecast.temperatureF}</td>
                        <td>{forecast.summary}</td>
                    </tr>
                )}
            </tbody>
        </table>;
    }
}

App.js

import React, {Component} from "react";
import {Route, Switch, BrowserRouter} from 'react-router-dom';

import Layout from './containers/Layout';;
import PlantInfo from './components/PlantInfo';
import Home from './components/Home';

class App extends Component {
    render() {
        return (
            <BrowserRouter>
                <Layout>
                    <Switch>
                        <Route path="/" exact component={Home}></Route>
                        <Route path="/plantInfo" component={PlantInfo}></Route>
                    </Switch>
                </Layout>
            </BrowserRouter>

        );
    }
}
export default App;

Webpack.config

const path = require('path');
const webpack = require('webpack');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");


module.exports = {
    mode:"development",
    entry: { 'main': './wwwroot/src/index.js' },

    output: {
        path: path.resolve(__dirname, 'wwwroot/dist'),
        filename: 'bundle.js',
        publicPath: 'dist/'
    },
    plugins: [
        new webpack.ProvidePlugin({
            $: 'jquery',
            jQuery: 'jquery',
            'window.jQuery': 'jquery',
            Popper: ['popper.js', 'default']
        }),
        new MiniCssExtractPlugin({
            // Options similar to the same options in webpackOptions.output
            // both options are optional
            filename: "[name].css",
            chunkFilename: "[id].css"
        })

    ],
    module: {
        rules: [
            {
                test: /\.css$/,
                use: [
                    {
                        loader: MiniCssExtractPlugin.loader,
                        options: {
                            // you can specify a publicPath here
                            // by default it use publicPath in webpackOptions.output
                            publicPath: '../'
                        }
                    },
                    "css-loader"
                ]
            },
            {
                test: /\.js?$/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: ['@babel/preset-env',
                                  '@babel/react',{
                                  'plugins': ['@babel/plugin-proposal-class-properties']
                            }
                        ]
                    }
                }
            },
        ]
    }
};

Startup.cs

 public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddRouteAnalyzer();


        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
            {
                HotModuleReplacement = true
            });

            app.UseStaticFiles();


            app.UseMvc(routes =>
            {

                routes.MapRoute(
                name: "areas",
                template: "{area:exists}/{controller=Home}/{action=index}/{id}"
                    );
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}"

                );

                routes.MapRouteAnalyzer("/routes");
            });
        }
    }

0 个答案:

没有答案