Ad

Koa + XMLHttpRequest: No 'Access-Control-Allow-Origin' Header Is Present On The Requested Resource

- 1 answer

I have simple koa server deployed on Heroku and use XMLHttpRequest for ajax. In my post request I get error message:

Access to XMLHttpRequest at 'https://upload-file-endpoint.herokuapp.com//upload-file' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

server.js

const Koa = require('koa');
const Router = require('koa-router');
const cors = require('@koa/cors');
const serve = require('koa-static');
const path = require('path');
const koaBodyMultipart = require('koa-body')({ multipart: true });

var corsOptions = {
  origin: '*'
};

const app = new Koa();
app.use(cors(corsOptions));
app.use(serve(path.join(process.env.PWD, '/dist')));

const router = new Router();

router
  .post('/upload-file', koaBodyMultipart, (ctx, next) => {
    const { file } = ctx.request.files;
    if (file) {
        ctx.response.body = ctx.request.body;
    } else {
        ctx.throw(500,'Error Message');
    }
  })
  .post('/upload-file-error', koaBodyMultipart, (ctx, next) => {
    ctx.throw(500,'Error Message');
  });

app.use(router.routes()).use(router.allowedMethods());

// don't listen to this port if the app is required from a test script
if (!module.parent) {
  var server = app.listen(process.env.PORT || 1337);
  var port = server.address().port;
  console.log('running at port:' + port)
}

ajax post request

var file = fileUpl.getFile();
const xhr = new XMLHttpRequest();

xhr.open("POST", "https://upload-file-endpoint.herokuapp.com//upload-file", true);
xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
var formData = new FormData();
formData.append("file", file);
xhr.send(formData);

I am using @koa/cors library. I tried to initialize cors with and without corsOptions.

package.json

"dependencies": {
    "@koa/cors": "^3.0.0",
    "koa": "^2.7.0",
    "koa-body": "^4.1.0",
    "koa-router": "^7.4.0",
    "koa-send": "^5.0.0",
    "koa-static": "^5.0.0"
  },
  "devDependencies": {
    "nodemon": "^1.19.1"
  }
Ad

Answer

When I try it now, it works. Server is deployed on Heroku.

I added

var corsOptions = {
  origin: '*'
};

Probably I didn't wait, when it was deploying on Heroku.

Ad
source: stackoverflow.com
Ad