简体   繁体   English

虽然 CORS 设置正确,但仍然发生 CORS 错误 - NODE 和 JAVASCRIPT

[英]Although CORS is Set Up Properly CORS Error Still Occurs- NODE and JAVASCRIPT

The code below simply uploads images to node server folder.下面的代码只是将图像上传到节点服务器文件夹。 When I was building on my localhost, everything was working fine and I understand because it was on the same machine.当我在本地主机上构建时,一切正常,我理解,因为它在同一台机器上。 However, once I pushed it to heroku server, I keep on getting Access to XMLHttpRequest at 'https://mydomainname.herokuapp.com/api/cars/images' from origin 'https://mydomainname.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.但是,一旦我将它推送到 heroku 服务器,我就会继续Access to XMLHttpRequest at 'https://mydomainname.herokuapp.com/api/cars/images' from origin 'https://mydomainname.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Followed by Failed to load resource: net::ERR_CONNECTION_RESET or sometimes Failed to load resource: net::ERR_FAILED I have tried everything on stackoverflow and I even uninstalled cors package and typed the cors code manually on the server side app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept,image"); next(); });其次是Failed to load resource: net::ERR_CONNECTION_RESET或有时Failed to load resource: net::ERR_FAILED我已经尝试了stackoverflow上的所有内容,我什至卸载了cors包并在服务器端手动输入了cors代码app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept,image"); next(); }); But that didnt work either.但这也没有用。 We have 20 different api routes and they all work fine.我们有 20 条不同的 api 路由,它们都运行良好。 Its just this api route that keeps getting cors issue.只是这个 api 路线不断出现 cors 问题。 I dont understand where Im going wrong because I have done everything to ensure the cors process works right.我不明白我哪里出错了,因为我已尽一切努力确保 cors 流程正常工作。 Any help will be greatly appreciated.任何帮助将不胜感激。

[BACKEND SERVER NODEJS]
const express = require('express');
const router = require("express").Router();
const bodyParser =  require('body-parser')
require('dotenv').config();
const https = require('https');
const port = process.env.PORT || 8000;
const app = express();
const cors = require('cors');

//Cors Configuration
app.use(cors())

//BodyParser middleware
app.use(express.json());

const postCarImages = (req,res)=>{
  try{
    let imageData = JSON.parse(req.headers["image"]).imageData

    if(!imageData){
      return res.status(404).json({
        status:404,
        message: "Error in Uploading Images"
      })
    }else{
      let projectFolderID = imageData[0].folderID
      let projectFolderName = imageData[0].image.folderName
      let number = imageData[0].image.number

      if(projectFolderID && projectFolderName && number){
        req.on('data',(chunk)=>{
          fs.appendFileSync(`./store_pictures_cars/${projectFolderID}/${projectFolderName}/Car ${number}.jpeg`,chunk,'base64')
        })

        return res.status(200).json({
          status: 200,
          message:'I am done with this one',
          folderName:projectFolderName
        })

      }else{
        return res.status(404).json({
          status:404,
          message: "Error in Uploading Images"
        })
      }

    }

  }catch(error){
    res.status(500).json({
      message:'Something went wrong. Please refresh page.'
    })
  }
}

router.post('/api/cars/images',postCarImages)

//Prevent application from crashing if incorrect route
app.all('*', (req, res, next) =>{
  const err = new Error(`Requested URL ${req.path} not found!`);
  err.statusCode = 404;
  next(err);
})

app.use((err, req, res, next) =>{
  const statusCode = err.statusCode || 500;
  res.status(statusCode).json({
    success: 0,
    message: err.message,
    stack: err.stack
  })
})


//Serve static files if in production
if(process.env.NODE_ENV === 'production'){

  //Set static folder
  app.use(express.static('client/build'));

  app.get('*', (req, res) =>{
    res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'))
  });
}



app.listen(port, () => console.log(`Server started on port ${port}`));

[FRONTEND HTML]
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=DM+Sans:ital@0;1&family=Heebo:wght@400;500&family=Lato:wght@400;700;900&family=Nunito+Sans:wght@300;400&family=Open+Sans&family=PT+Sans:wght@700&family=Roboto+Mono:wght@500&family=Roboto+Slab:wght@600&family=Roboto:wght@700;900&family=Rubik:wght@400;500&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons+Outlined"/>
    <link rel="stylesheet" href='style.css'>

    <title>Testing</title>
  </head>
  <body>
    <main id="main-container">
      <input id="images-folder" type="file" style="display: none;" accept="image/*" webkitdirectory directory multiple>
    </main>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.8/clipboard.min.js"></script>
    <script type="module" src="app.js"></script>
  </body>
</html>

[FRONTEND JAVASCRIPT]
function after_render(){
  const uploadImagesBtn = document.getElementById('images-folder')
  const folderID = "ID-1234Testing-Testing_Folder"

  uploadImagesBtn.addEventListener('change',(event)=>{

    uploadImages(event.target.files,folderID)
        event.target.value = ""
  })

}

async function renameFieldImages(images,id){
  const api = 'https://mydomainname.herokuapp.com/api/cars/images'
  let totalChunksCompleted = 0;
  let folderID = id;
  let projectFolderName = ''

let totalImagesUploadedProgress = []//Keep pushing total image size of an image once the 
image has been uploaded successfully

let totalImages = images.length//Get total number of images uploaded by the user

let percentCompleted = 0

  for(let i = 0; i < images.length; i++){
      const fileReader = new FileReader()

      //Send data to server
      let data = {
            imageData:[
             {
              folderID:folderID,
               image:{
                 folderName:'Testing_Image_Folder_1',
                 number: '1'
               }
             }
           ],
      }


      fileReader.readAsArrayBuffer(images[i])

      let request = new XMLHttpRequest()
      request.open('POST',api,true)
      request.setRequestHeader("Content-Type", "application/octet-stream");
      request.setRequestHeader("image", JSON.stringify(data));

      fileReader.addEventListener('load',(event)=>{


      request.send(event.target.result)
      })


      request.upload.onprogress = function({loaded, total}){

            let completedImage = Math.floor(loaded/total) * 100

            if(completedImage === 100){

              totalImagesUploadedProgress.push(total)

              percentCompleted = Math.floor((totalImagesUploadedProgress.length/totalImages)*100)//Get percent completed

            }
      }
  }
}

Here are some things you could check:以下是您可以检查的一些事项:

Check if you are making calls from HTTP to HTTPS.检查您是否正在从 HTTP 调用 HTTPS。 That is when you get a CORS issue.那是您遇到CORS问题的时候。

Check if you have installed the SSL certificate properly.检查您是否已正确安装 SSL 证书。

Incorrect or corrupted TCP/IP configuration. TCP/IP 配置不正确或损坏。 Check this on your server.在你的服务器上检查这个。 Check inbound and outbound security rules.检查入站和出站安全规则。

Test your backend from Postman.从 Postman 测试您的后端。

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

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