繁体   English   中英

请求的资源上不存在“Access-Control-Allow-Origin”header。 上传不工作

[英]No 'Access-Control-Allow-Origin' header is present on the requested resource. Uploads are not working

I ran into this cors issue when i deployed my django project which is using the django rest api and netlify for the frontend. 我在这里尝试了一些解决方案,但对我来说没有任何效果: CORS_ORIGIN_ALLOW_ALL = True 前端可能缺少一些东西吗? 有没有办法获得有关问题到底是什么的更多详细信息? 这似乎只发生在我的上传表单上。 (我添加了下面的代码)它在我使用 docker 的本地机器上运行良好。

Access to XMLHttpRequest at 'https://domain/dj-rest-auth/user/' from origin 'https://domain' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

patch https://domain/dj-rest-auth/user/ net::ERR_FAILED 400
import { useState } from 'react';
import { Formik, Field, Form, ErrorMessage } from 'formik';
import axios from "axios"
import { API } from '../api'
import { useDispatch, useSelector } from "react-redux";
import { setInfo } from "../store/userInfoSlice";
import { Button, message, Upload } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import ImgCrop from 'antd-img-crop';

import {
    Spin
  } from 'antd';


export function Profile() {
    const info = useSelector((state) => state.userInfo.value);
    const accessToken = useSelector((state) => state.tokens.value.accessToken);
    const [loading, setLoading] = useState(false)
    const dispatch = useDispatch();

    const onUploadDraggerChange = ({ fileList: newFileList, file: resp }) => {
        setFileList(newFileList);
    
        if (!resp || !resp.response || !resp.response.profile) {
          return;
        }
    
        dispatch(setInfo(resp.response));
        message.success("Updated your profile picture")
      };

    const [fileList, setFileList] = useState([
        {
          uid: '-1',
          name: 'image.png',
          status: 'done',
          url: info.profile.avatar,
        },
      ]);

      const uploadDraggerrops = {
        name: 'profile.avatar',
        action: API.auth.userdetails,
        method: 'patch',
        listType: "picture-card",
        maxCount: 1,
        onChange: onUploadDraggerChange,
        fileList: fileList,
        headers: {
            "Authorization": `Bearer ${accessToken}`
        },
        withCredentials: true,
    };

    function handleSubmit(values) {
        setLoading(true)
        const data = new FormData()

        data.append("first_name", values.first_name || "");
        data.append("last_name", values.last_name || "");


        axios.patch(API.auth.userdetails, data, {
            headers: {
                "Authorization": `Bearer ${accessToken}`
            },
            withCredentials: true,
        })
            .then(res => {
                dispatch(setInfo(res.data));
                message.success("Updated your profile")
            })
            .finally(() => {
                setLoading(false)
            })
    }
    

    return (
        <div>
            {loading && (
                <Spin />
            )}
            {info && (
                <div>
                    <h1>Edit Profile</h1>
                    
                    <Formik
                        initialValues={{
                            
                            first_name: info.first_name,
                            last_name: info.last_name,
                        }}     

                        onSubmit={handleSubmit}>

                        {({ errors, touched }) => (
                            <Form>
                                <ImgCrop>
                            <Upload.Dragger {...uploadDraggerrops}>
                                <Button icon={<UploadOutlined />}>Click to Upload</Button>
                            </Upload.Dragger>
                            </ImgCrop>
                                <Field name="first_name">
                                    {({ field, form }) => (
                                        <label className="mt-3 block">
                                            <span className="text-gray-700">first name</span><br></br>
                                            <input
                                            {...field}
                                            type="text"
                                            className="
                                                mt-2
                                                block
                                                rounded-md
                                                border-gray-300
                                                shadow-sm
                                                focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50
                                            "
                                            style={
                                                form.touched.first_name && form.errors.first_name ? (
                                                    { border: '2px solid var(--primary-red)'}
                                                ) : null
                                            }
                                            />
                                        </label>
                                    )}
                                </Field>
                               <br></br>
                                <Field name="last_name">
                                    {({ field, form }) => (
                                        <label className="mt-3 block">
                                            <span className="text-gray-700">last name</span><br></br>
                                            <input
                                            {...field}
                                            type="text"
                                            className="
                                                mt-2
                                                block
                                                rounded-md
                                                border-gray-300
                                                shadow-sm
                                                focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50
                                            "
                                            style={
                                                form.touched.last_name && form.errors.last_name ? (
                                                    { border: '2px solid var(--primary-red)'}
                                                ) : null
                                            }
                                            />
                                        </label>
                                    )}
                                </Field>

                                <div className='editserror'><ErrorMessage name="AdministratorCell" /></div>
                                <div className="flex items-center">
                                <label className="mt-3 block">
                                </label>
                            </div>
                                <button type="submit" className="btn btn-g">Update</button>
                            </Form>
                        )}
                    </Formik>
                </div>
            )}
        </div>
    )

}

发现问题:这是由于我的 JS 中没有大写 PATCH 造成的。 显然在本地主机上这不是问题。

暂无
暂无

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

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