首页 > 解决方案 > 如何将请求 Axios 从 React JS 发布到 ASP.NET Core

问题描述

我想将我在 React JS 中创建的表单信息发布到 ASP.Net Core。我在 React 端使用 axios 库进行 HTTP 操作。

我有两个不同的问题。

1-) 是否与在 ASP.Net Core 端未站立的 vendorRegistrationController.cs 文件有关?

2-) axios post 过程是否在 React 端正确完成?如果有任何遗漏,您能否提供文档或评论?

先感谢您。

VendorRegistrationController.cs

namespace Bait.Controllers
{
[Produces("application/json")]
[Route("api/controller")]
[ApiController]
[EnableCors("ReactPolicy")]

public class VendorRegistrationController : Controller
{
    private readonly VendorRegistrationService vendorRegistrationService;

    public VendorRegistrationController(VendorRegistrationService vendorRegistrationService)
    {
        this.vendorRegistrationService = vendorRegistrationService;
    } 

    [HttpGet]
    public IEnumerable<VendorRegistration> Get()
    {
        return vendorRegistrationService.GetAll();
    }

    [HttpGet("{id}")]
    public async Task<IActionResult> Get(int id)
    {
        return Ok(vendorRegistrationService.GetById(id));
    }

    [HttpPost]
    public async Task<IActionResult> Post([FromBody] VendorRegistration vendorRegistration)
    {
        return CreatedAtAction("Get", new { id = vendorRegistration.VendorCustomerID }, vendorRegistrationService.Create(vendorRegistration));
    }

    [HttpPut("{id}")]
    public async Task<IActionResult> Put(int id, [FromBody] VendorRegistration vendorRegistration)
    {
        vendorRegistrationService.Update(id, vendorRegistration);
        return NoContent();
    }

    [HttpDelete("{id}")]
    public async Task<IActionResult> Delete(int id)
    {
        vendorRegistrationService.Delete(id);
        return NoContent();
    }

    public override NoContentResult NoContent()
    {
        return base.NoContent();
    }
  }
 }

启动.cs

namespace Bait
{
 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.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });

        services.AddCors(o => o.AddPolicy("ReactPolicy", builder =>
        {
            builder.AllowAnyOrigin()
                   .AllowAnyMethod()
                   .AllowAnyHeader();
        }));

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    }

    // 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();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }

        app.UseStaticFiles();
        app.UseCookiePolicy();

        app.UseCors("ReactPolicy");
        app.UseHttpsRedirection();

        app.UseMvc();

      }
     }
   }

组件注册表格.tsx

     import {axios} from 'axios'

     interface User {
      firstName: 'Alex';
      }


   const axios = require('axios').default;

  const RegistrationForm = () => {
    const [sameAsShipping, setSameAsShipping] = useState(false)
    const router = useRouter()
    const classes = useStyles()
    const bull = <span className={classes.bullet}>•&lt;/span>

    const handleFormSubmit = async (values: any) => {
      console.log(values)
    }

  useEffect(() => {
     // Use [] as second argument in useEffect for not rendering each time
    axios.post<User>('https://localhost:5001/api/vendorregistration')
   .then((response) => {
      console.log(response.data);
    });
  }, []);

  const handleCheckboxChange =
      (values: typeof initialValues, setFieldValue: any) => (e: any, _: boolean) => {
      const checked = e.currentTarget.checked

     setSameAsShipping(checked)
     setFieldValue('same_as_shipping', checked)
     setFieldValue('billing_name', checked ? values.shipping_name : '')
  }

 return (
   <Formik
     initialValues={initialValues}
     validationSchema={checkoutSchema}
     onSubmit={handleFormSubmit}
   >
    {({
    values,
    errors,
    touched,
    handleChange,
    handleBlur,
    handleSubmit,
    setFieldValue,
  }) => (
    <form onSubmit={handleSubmit}>
      <Card1 sx={{ mb: '2rem' }}>
       <Typography  variant="h4" align="center" fontWeight="800" mb={2}>
          Create Your Vendor Account
       </Typography>

        <Typography fontWeight="600" mb={2}>
          Account Info
        </Typography>

        <Grid container spacing={6}>
          <Grid item sm={6} xs={12}>
            <TextField
              name="first_name"
              label="First Name*"
              fullWidth
              sx={{ mb: '1rem' }}
              onBlur={handleBlur}
              onChange={handleChange}
              value={values.first_name || ''}
              error={!!touched.first_name && !!errors.first_name}
              helperText={touched.first_name && errors.first_name}
            />
            <TextField
              name="vendor_name"
              label="Company Name*"
              fullWidth
              sx={{ mb: '1rem' }}
              onBlur={handleBlur}
              onChange={handleChange}
              value={values.vendor_name || ''}
              error={!!touched.vendor_name && !!errors.vendor_name}
              helperText={touched.vendor_name && errors.vendor_name}
            />
            <TextField
              name="password"
              label="Password*"
              fullWidth
              sx={{ mb: '1rem' }}
              onBlur={handleBlur}
              onChange={handleChange}
              value={values.password || ''}
              error={!!touched.password && !!errors.password}
              helperText={touched.password && errors.password}
            />
            <Autocomplete
              options={countryList}
              getOptionLabel={(option) => option.label || ''}
              value={values.shipping_country}
              sx={{ mb: '1rem' }}
              fullWidth
              onChange={(_e, value) => setFieldValue('shipping_country', value)}
              renderInput={(params) => (
                <TextField
                  label="Country"
                  placeholder="Select Country"
                  variant="outlined"
                  size="small"
                  error={!!touched.shipping_country && !!errors.shipping_country}
                  helperText={
                    touched.shipping_country && errors.shipping_country
                  }
                  {...params}
                />
              )}
            />
            <TextField
              name="address1"
              label="Address Line 1*"
              fullWidth
              sx={{ mb: '1rem' }}
              onBlur={handleBlur}
              onChange={handleChange}
              value={values.address1 || ''}
              error={!!touched.address1 && !!errors.address1}
              helperText={touched.address1 && errors.address1}
            />
            <TextField
              name="zip_code"
              label="Zip Code*"
              type="number"
              fullWidth
              onBlur={handleBlur}
              onChange={handleChange}
              value={values.zip_code || ''}
              error={!!touched.zip_code && !!errors.zip_code}
              helperText={touched.zip_code && errors.zip_code}
            />
            
          </Grid>
          <Grid item sm={6} xs={12}>
             <TextField
              name="last_name"
              label="Last Name*"
              fullWidth
              sx={{ mb: '1rem' }}
              onBlur={handleBlur}
              onChange={handleChange}
              value={values.last_name || ''}
              error={!!touched.last_name && !!errors.last_name}
              helperText={touched.last_name && errors.last_name}
            />
            <TextField
              name="email_address"
              label="Email Address*"
              type="email"
              fullWidth
              sx={{ mb: '1rem' }}
              onBlur={handleBlur}
              onChange={handleChange}
              value={values.email_address || ''}
              error={!!touched.email_address && !!errors.email_address}
              helperText={touched.email_address && errors.email_address}
            />
            <TextField
              name="confirm_password"
              label="Confirm Password*"
              fullWidth
              sx={{ mb: '1rem' }}
              onBlur={handleBlur}
              onChange={handleChange}
              value={values.confirm_password || ''}
              error={!!touched.confirm_password && !!errors.confirm_password}
              helperText={touched.confirm_password && errors.confirm_password}
            />
             <TextField
              name="state"
              label="State*"
              fullWidth
              sx={{ mb: '1rem' }}
              onBlur={handleBlur}
              onChange={handleChange}
              value={values.state || ''}
              error={!!touched.state && !!errors.state}
              helperText={touched.state && errors.state}
            />
            <TextField
              name="address2"
              label="Address Line 2*"
              fullWidth
              sx={{ mb: '1rem' }}
              onBlur={handleBlur}
              onChange={handleChange}
              value={values.address2 || ''}
              error={!!touched.address2 && !!errors.address2}
              helperText={touched.address2 && errors.address2}
            />
            <TextField
              name="phone_number"
              label="Phone Number"
              fullWidth
              onBlur={handleBlur}
              onChange={handleChange}
              value={values.phone_number || ''}
            />
          </Grid>
        </Grid>
      </Card1>

      <Card1 sx={{ mb: '2rem' }}>
        <Typography fontWeight="600" mb={2}>
          Additional Information / Accept Terms
        </Typography>

        {!sameAsShipping && (
          <Grid container spacing={6}>
            <Grid item sm={6} xs={12}>
            <Autocomplete
                options={countryList}
                getOptionLabel={(option) => option.label || ''}
                value={values.billing_country}
                sx={{ mb: '1rem' }}
                fullWidth
                onChange={(_e, value) => setFieldValue('billing_country', value)}
                renderInput={(params) => (
                  <TextField
                    label="Shop Type"
                    placeholder="Shop Type"
                    error={!!touched.billing_country && !!errors.billing_country}
                    helperText={
                      touched.billing_country && errors.billing_country
                    }
                    {...params}
                  />
                )}
              />
              <Autocomplete
                options={countryList}
                getOptionLabel={(option) => option.label || ''}
                value={values.billing_country}
                sx={{ mb: '1rem' }}
                fullWidth
                onChange={(_e, value) => setFieldValue('billing_country', value)}
                renderInput={(params) => (
                  <TextField
                    label="I'm interested in learning more about..."
                    placeholder="I'm interested..."
                    error={!!touched.billing_country && !!errors.billing_country}
                    helperText={
                      touched.billing_country && errors.billing_country
                    }
                    {...params}
                  />
                )}
              />
              <TextField
                name="billing_contact"
                label="How did your hear about BaitMrkt?"
                fullWidth
                sx={{ mb: '1rem' }}
                onBlur={handleBlur}
                onChange={handleChange}
                value={values.billing_contact || ''}
                error={!!touched.billing_contact && !!errors.billing_contact}
                helperText={touched.billing_contact && errors.billing_contact}
              />
              <Grid container sx={{mt: '4rem'}}>
                <FormControlLabel
                 label={
                  <FlexBox>
                    I agree to the BaitMrkt
                      <H6 ml={1} color= "#D11C25">
                        Terms & Conditions
                      </H6>
                      <Span ml={1}>
                      and
                      </Span>
                    <H6 ml={1} color= "#D11C25">
                    Privacy Policy*
                      </H6>
                  </FlexBox>
                }
                 control={<Checkbox size="small" color="secondary" />}
                 sx={{
                  zIndex: 1,
                  position: 'relative',
                 }}
                 onChange={handleCheckboxChange(values, setFieldValue)}
                />
          
              </Grid>

             <Grid container>
              <FormControlLabel
                 label={
                  <FlexBox>
                   I agree to receive account updates and other vendor specific
                   information via email.*
                  </FlexBox>
                }
                 control={<Checkbox size="small" color="secondary" />}
                 sx={{
                  zIndex: 1,
                  position: 'relative',
                }}
               onChange={handleCheckboxChange(values, setFieldValue)}
              /> 
        </Grid>      

            </Grid>
          </Grid>
        )}
      </Card1>
      <Grid container>
        <Grid item sm={6} xs={12}>
          <Button variant="contained" color="primary" type="submit">
            REGISTER
          </Button>
        </Grid>
      </Grid>

    </form>
  )}
 </Formik>
   )
  }
 export default RegistrationForm

在此处输入图像描述

标签: reactjsasp.net-mvcasp.net-coreasp.net-web-apiaxios

解决方案


用来[Route("api/{controller}")]替换你的[Route("api/controller")]


推荐阅读