繁体   English   中英

从源 'http://localhost:3000' 在 'http://127.0.0.1:5000/product' 访问 XMLHttpRequest

[英]access to XMLHttpRequest at 'http://127.0.0.1:5000/product' from origin 'http://localhost:3000'

我正在尝试从我的前端(反应)向我的后端(python、flask 和 MySql)发出 POST 请求,但我收到此错误消息。

Access to XMLHttpRequest at 'http://127.0.0.1:5000/product' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

在此处输入图像描述

网络选项卡错误消息在此处输入图像描述

我在服务器终端上得到这个,它没有显示 POST 方法。 在此处输入图像描述

发出 GET 请求时我没有收到此错误消息,它只发生在 POST 请求中,但如果我从 POSTMAN 发出,POST 工作正常。

前端表单代码

import React, { useState } from "react";
import { useDispatch } from "react-redux";
import { createProduct } from "../../actions/products";
import Button from "./Button";
import Input from "./Input";
import Label from "./Label";

const Modal = ({ showModal, setShowModal }) => {
  const dispatch = useDispatch();
  const [name, setName] = useState("");
  const [unit, setUnit] = useState();
  const [pricePerUnit, setPricePerUnit] = useState();

  const handleSubmit = async (e) => {
    e.preventDefault();
    const product = {
      product_name: name,
      uom_id: parseInt(unit),
      price_per_unit: parseInt(pricePerUnit),
    };
    console.log(product);
    await dispatch(createProduct(product));
  };

  return (
                  <form onSubmit={handleSubmit}>
                    <div>
                      <Label children="Name" />
                      <Input
                        children="Name"
                        type="text"
                        value={name}
                        onChange={(e) => setName(e.target.value)}
                      />
                    </div>
                    <div>
                      <Label children="Unit" />
                      <Input
                        children="Unit"
                        type="number"
                        value={unit}
                        onChange={(e) => setUnit(e.target.value)}
                      />
                    </div>
                    <div>
                      <Label children="Price Per Unit" />
                      <Input
                        children="Price Per Unit"
                        type="number"
                        value={pricePerUnit}
                        onChange={(e) => setPricePerUnit(e.target.value)}
                      />
                    </div>
                    <div className="flex items-center justify-end py-6 border-t border-solid border-blueGray-200 rounded-b">
                      <button
                        className="text-red-500 background-transparent font-bold uppercase px-6 py-2 text-sm outline-none focus:outline-none mr-1 mb-1 ease-linear transition-all duration-150"
                        type="button"
                        onClick={() => setShowModal(false)}
                      >
                        Close
                      </button>
                      <Button type="submit">Save</Button>
                    </div>
                  </form>
  );
};

export default Modal;

创建产品操作

import * as api from "../api";
export const createProduct = (product) => async (dispatch) => {
  try {
    const { data } = await api.createProduct(product);
    dispatch({ type: "CREATE", payload: data });
    // toast.success("Product submitted");
  } catch (error) {
    console.log(error);
    // toast.error(error.message);
  }
};

../api API 代码

import axios from "axios";
const API = axios.create({ baseURL: process.env.REACT_APP_BASE_URL });

export const createProduct = (newProduct) =>
  API.post("/product", newProduct);

后端代码:

@app.route('/product', methods=['POST'])
def insert_product():
    request_payload = request.json
    print(request_payload)
    product_id = products_dao.insert_new_product(connection, request_payload)
    response = jsonify({
        'product_id': product_id
    })
    response.headers.add('Access-Control-Allow-Origin', '*')
    return response

Postman 请求截图在此处输入图像描述

在此处输入图像描述

预检请求截图在此处输入图像描述

CORS 问题是由跨域请求引起的。 确保服务器已设置 CORS 设置并返回Access-Control-Allow-Origin: * header。 预检将检查是否允许跨站点请求,然后才会发生真正的请求。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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