简体   繁体   中英

Access error between API and UI (react JS)

I created UI part in JS using React (It's my first experience - here could be errors). Also I created Backend part - it works good, I tested it. When I tried unite it - I get this error. I have a problem with access -> when user click on a submit button (I get this error) 在此处输入图片说明

Could you explain what I did wrong. I think my UI part is good, I think problem in an API part. I attached both: UI (react JS) :

import React from 'react';
import { Link } from 'react-router-dom';
import { notification, Alert, Spin, Form, Input, Button, Typography } from 'antd';
import { usePromise } from 'innroad.common.ui';
import * as apiService from 'services/ApiService';
import { LAYOUT, TAIL_LAYOUT } from 'constants/layouts';
import styles from './AddTownCreation.scss';

const AddTownCreation = () => {
  const onFail = () => notification.error({ message: 'some error occured while creating template' });

  const [{ data, isLoading }, createNewTown] = usePromise(apiService.createTown, { initialData: [], onFail });

  const handleFormFinish = (formValue) => createNewTown(formValue);

  return (
    <>
      <Spin spinning={isLoading}>
        <Typography.Title>Create New Town</Typography.Title>
        {data.length > 0 && (<Alert message={`New town id : ${data.join(',')}`} type="info" />)}
        <Form {...LAYOUT} onFinish={handleFormFinish}>
          <Form.Item
            name="name"
            label="Town Name :"
            rules={[{ whitespace: true, required: true, message: 'This is required field' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item {...TAIL_LAYOUT}>
            <Button htmlType="submit" className={styles.rightMargin}>Submit</Button>
            <Button type="link" className="ant-btn"><Link to="/">Cancel</Link></Button>
          </Form.Item>
        </Form>
      </Spin>
    </>
  );
};

export default AddTownCreation;

API in JS :

import { get, post } from './HttpService';

/**
 * ---------------------------------
 * endpoints
 * ---------------------------------
 */

export const createTown = async (data) => post('/add.town', data);

API that I created in C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using innRoad.innSupportTools.Services;
using innRoad.innSupportTools.ViewModels;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

{
    [Route("api")]
    [ApiController]
    public class TownController : ControllerBase
    {
        public readonly ITownService _townService;

        public TownController(ITownService townService)
        {
            _townService = townService;
        }

        [HttpPost]
        [Route("add.town")]
        public async Task<int> InsertTown([FromBody] TownViewModel town)
        {
            return await _townService.InsertTown(town.Name);
        }

        [HttpGet]
        [Route("GetTown/{townId}")]
        public async Task<TownViewModel> GetTown(int townId)
        {
            return await _townService.GetTown(townId);
        }
    }
}

TownViewModel

{
    public class TownViewModel
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}

Backend part works good

尝试在控制器顶部添加 [EnableCors("AllowAll")]

Browsers are implemented with same-origin policy - this means that any request across domain boundaries (different origin) are blocked by default. But this is a common use case - that you want to get a public resource from a different origin. For example, you will need to get data from a third party provider.

To make this work, the server that provides data needs let the browser know that "the origin where the request is coming from can access my resource/data". The browser remembers that and allows cross-origin resource sharing.

Step 1: Browser

When the browser is making a cross-origin request, the browser adds an Origin header with the current origin (scheme, host, and port).

Step 2: server

On the server side, when a server sees this header, and wants to allow access, it needs to add an Access-Control-Allow-Origin header to the response specifying the requesting origin (or * to allow any origin.)

Step 3: browser receives response

When the browser sees this response with an appropriate Access-Control-Allow-Origin header, the browser allows the response data to be shared with the client site.

So if you want to take the application to production then what you need to implement is step 2, check the origin header for the requests if it is from a valid whitelisted URL (like your UI application url) then set the Access-Control-Allow-Origin header.

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