Saturday 16 June 2018

react axios + aspcore webapi

axios get data from webapi


axios post to webapi, items are added

axios delete request to webapi, item with id '2' is deleted

axios update request to webapi, item id '3' sam->Sam true->false

axios try to delete and update item id '4', item not found on webapi, error response

stop webapi, axios receives network error response

webapi header

webapi

 webapi startup.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.EntityFrameworkCore;
using webApi.Models;

namespace webApi
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddPolicy("AllowAllOrigins", builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());

            });
            services.AddDbContext<Context>(opt =>
                opt.UseInMemoryDatabase("MyApiDb"));
            services.AddMvc();
        }

        // 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.UseCors("AllowAllOrigins");
            app.UseMvc();
        }
    }
}

-----------------------------------------------------------------------------
webapi ItemsController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using webApi.Models;

namespace webApi.Controllers
{
    [Produces("application/json")]
    [Route("api/values")]
    [EnableCors("AllowAllOrigins")]
    public class ItemsController : Controller
    {
        private readonly Context _context;

        public ItemsController(Context context)
        {
            _context = context;


            if (_context.Items.Count() == 0)
            {
                _context.Items.Add(new Item
                {
                    Name = "bob",
                    IsComplete = true,
                });

                _context.SaveChanges();
            }
        }

        // GET: api/values
        [HttpGet]
        public IEnumerable<Item> GetItems()
        {
            return _context.Items.ToList();
        }

        // GET: api/values/5
        [HttpGet("{id}")]
        public async Task<IActionResult> GetItem([FromRoute] int id)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var item = await _context.Items.SingleOrDefaultAsync(m => m.Id == id);

            if (item == null)
            {
                return NotFound();
            }

            return Ok(item);
        }

        // PUT: api/values/5
        [HttpPut("{id}")]
        public async Task<IActionResult> PutItem([FromRoute] int id, [FromBody] Item item)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (id != item.Id)
            {
                return BadRequest();
            }

            _context.Entry(item).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ItemExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return Ok();
        }

        // POST: api/values
        [HttpPost]
        public async Task<IActionResult> PostItem([FromBody] Item item)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            _context.Items.Add(item);
            await _context.SaveChangesAsync();

            return CreatedAtAction("GetItem", new { id = item.Id }, item);
        }

        // DELETE: api/values/5
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteItem([FromRoute] int id)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var item = await _context.Items.SingleOrDefaultAsync(m => m.Id == id);
            if (item == null)
            {
                return NotFound();
            }

            _context.Items.Remove(item);
            await _context.SaveChangesAsync();

            return Ok(item);
        }

        private bool ItemExists(int id)
        {
            return _context.Items.Any(e => e.Id == id);
        }
    }
}

-------------------------------------------------------------------------
webapi context.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;

namespace webApi.Models
{
    public class Context:DbContext
    {
        public Context(DbContextOptions<Context> options)
            : base(options)
        {
        }

        public DbSet<Item> Items { get; set; }
    }
}

----------------------------------------------------------
webapi Item.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace webApi.Models
{
    public class Item
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public bool IsComplete { get; set; }
    }
}

---------------------------------------------------------
react app.js

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import axios from 'axios';
import { Button, Form, FormGroup, Input } from 'reactstrap';

class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            items: [],
            name_input: "",
            name_update: "",
            iscomplete_input: "",
            iscomplete_update:"",
            delete_id: -1,
            update_id: -1,
            get_status: "",
            add_status: "",
            delete_status: "",
            update_status: "",
        }
    }

    handle_getAll() {

        axios.get(myUrl)
            .then(res => {
                const Data = res.data;
                this.setState({ items: Data });
                res.statusText ? this.setState({ get_status: res.statusText }) : null;
            })
            .catch(error => {
                this.setState({ get_status: error.message })
            });
    }

    handle_post(e) {
        e.preventDefault();

        const name = this.state.name_input;
        const complete = this.state.iscomplete_input === "true" ? true : false;

        if (name !== "") {
            axios.post(myUrl, { name: name, isComplete: complete })
                .then(res => {
                    console.log(res);
                    console.log(res.data);
                    res.statusText ? this.setState({ add_status: res.statusText }) : null;

                    return this.handle_getAll();
                })
                .catch(error => {
                    this.setState({ add_status: error.message })
                });
        }

    }

    handle_delete(e) {
        e.preventDefault();

        const id = this.state.delete_id;
        const delete_url = myUrl + '/' + id.toString();

        axios.delete(delete_url)
            .then(res => {
                console.log(res);
                console.log(res.data);
                res.statusText ? this.setState({ delete_status: res.statusText }) : null;

                return this.handle_getAll();
            })
            .catch(error => {
                this.setState({ delete_status: error.message });
            });

    }

    handle_update(e) {
        e.preventDefault();

        const id = this.state.update_id;
        const update_url = myUrl + '/' + id.toString();
        const name = this.state.name_update;
        const complete = this.state.iscomplete_update === "true" ? true : false;

        if (name !== "") {
            axios.put(update_url, { id: id, name: name, isComplete: complete })
                .then(res => {
                    console.log(res);
                    console.log(res.data);
                    res.statusText ? this.setState({ update_status: res.statusText }) : null;

                    return this.handle_getAll();
                })
                .catch(error => {
                    this.setState({ update_status: error.message })
                });
        }
    }

    render() {
        const show_state = {
            name_input: this.state.name_input,
            name_update: this.state.name_update,
            isComplete_input: this.state.iscomplete_input,
            isComplete_update: this.state.iscomplete_update,
            delete_id: this.state.delete_id,
            update_id: this.state.update_id,
            get_status: this.state.get_status,
            add_status: this.state.add_status,
            delete_status: this.state.delete_status,
            update_status: this.state.update_status,
        }

        const show_state_by_line = JSON.stringify(show_state).split(",").
            map((item, index) => (
                <div key={index}>{item}</div>
            ));

        const complete_options = [
            <option key={1}>false</option>,
            <option key={2}>true</option>
            ]

        return (
            <div >
                this.state:
                {show_state_by_line}
                <br />

                <Button size="sm" onClick={() => this.handle_getAll()}> get all</Button>
                {this.state.get_status}
                {arrayToString_func(this.state.items)}

                <Form inline onSubmit={(e) => this.handle_post(e)}>
                    <FormGroup >
                        add item:
                        <Input type="text" bsSize="sm" placeholder="name" required="required"
                            onChange={(e) => this.setState({ name_input: e.target.value, add_status: "" })} />
                        <Input type="select" bsSize="sm"
                            onChange={(e) => this.setState({ iscomplete_input: e.target.value, add_status: "" })}>
                            {complete_options}</Input>
                        {this.state.add_status}
                    </FormGroup>

                    <Button size="sm" type="submit"> post</Button>
                </Form>
                <br />

                <Form inline onSubmit={(e) => this.handle_delete(e)}>
                    <FormGroup >
                        Delete id:
                        <Input type="number" bsSize="sm" placeholder={-1} required="required"
                            onChange={(e) => this.setState({ delete_id: parseInt(e.target.value), delete_status: "" })} />
                        {this.state.delete_status}
                    </FormGroup>

                    <Button size="sm" type="submit"> delete</Button>
                </Form>
                <br />

                <Form inline onSubmit={(e) => this.handle_update(e)}>
                    <FormGroup >
                        Update id:
                        <Input type="number" bsSize="sm" placeholder={-1} required="required"
                            onChange={(e) => this.setState({ update_id: parseInt(e.target.value), update_status: "" })} />
                        <Input type="text" bsSize="sm" placeholder="name" required="required"
                            onChange={(e) => this.setState({ name_update: e.target.value, update_status: "" })} />
                        <Input type="select" bsSize="sm"
                            onChange={(e) => this.setState({ iscomplete_update: e.target.value, update_status: "" })}>
                            {complete_options}</Input>
                        {this.state.update_status}
                    </FormGroup>

                    <Button size="sm" type="submit"> update</Button>
                </Form>
            </div>
        );
    }
}

const arrayToString_func = (array_input) => (
    <ul>{
        array_input.map((item, index) => (
            <li key={index}>{JSON.stringify(item)}</li>
        ))
    }
    </ul>
);

const myUrl = "http://localhost:53664/api/values";

export default App;

-----------------------------------------------------------
reference:

http://chuanshuoge2.blogspot.com/2018/06/react-aspnet.html

No comments:

Post a Comment