Search code examples
reactjsfetchantdhapi

CORS issue in Antd request not passing CORS but fetch() does PASS


I am stucked with weired issue while using Antd for my backend UI. I am trying to includes Antd Upload for uploading images to my API server.

But due to some reason the normal fetch() seems to work fine while Antd internal fetch request shows error regarding CORS missing.

Note: The CORS in Hapi API server is active

Following is code of Antd

<Upload name="design_images" multiple
    action='http://localhost:4000/files/upload'
    
    beforeUpload={(file)=> {
        var formData = new FormData();
        //append formdata
        formData.append('myfiles',file);
        console.log(file)
        
        //normal fetch request 
        fetch('http://localhost:4000/files/upload',{
            method: 'POST', body: formData,
        }).then(res => res.json()).then(res => {
            
            //console.log(res)
        });
    }}
    
    onChange={(filesData) => { 
        let fileList = [];
        
        //foreach files in filelist from antd upload
        filesData.fileList.forEach((file) => {
            fileList.push(file.originFileObj); //pushing File object
        });
        
        //set value to formik
        setFieldValue("design_images", fileList);
    }}
>
    <Button icon={<UploadOutlined />}>Click to Upload</Button>
</Upload>

Following is the screenshot of the console

Screenshot the console with XHR request

Let me know if you need any further information.

Thanks in Advance.


Solution

  • A quick way to overcome CORS is from your backend.
    Install the third-party package CORS, then require the package at the topmost of your server index file ( Mostly App.js used by lots) , and use it as a middleware.

    var express = require('express')
    var cors = require('cors')
    var app = express()
     
    app.use(cors())
    

    And try making the request.