Gordienko R.
Gordienko R.

Reputation: 341

Can't get access to my local Rest API(koa using)

I've tried to create server using Koa.js:

const Koa = require('koa');
const router = require('koa-router'); 
const cors = require('koa-cors');
const app = new Koa();
const _ = router();

app.use(cors({origin: '*'}));

app.listen(3000, () => console.log('App running'));

_.post('/reg_new_user', postMessage);

function *postMessage() {
    this.body = 'New user was added' };

app.use(_.routes());

Then, I was gonna obtain simple responce from that server. Simple HTML page with form element(id='regForm') were created. Using following code I tried to make request:

const regForm = document.getElementById('reg_form');

function sendRegistrationData(event) {
    const data = new FormData(regForm);
    event.preventDefault();
    const regRequest = new XMLHttpRequest();
    regRequest.open('POST', 'localhost:3000/reg_new_user', true);
    regRequest.send(data);

    regRequest.onload = () => console.log(regRequest.responseText);
};

regForm.addEventListener('submit', sendRegistrationData);

But, when request happens, error message appears in console:

Failed to load localhost:3000/: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https

For sure, I've changed url parametr in my request to some other API and it works fine. According that experiment - there is a problem with my server.

What am I doing wrong?

Upvotes: 0

Views: 693

Answers (1)

Oles Savluk
Oles Savluk

Reputation: 4345

You forgot to specify protocol part of your URL string, for example:

...
regRequest.open('POST', 'http://localhost:3000/reg_new_user', true);

Upvotes: 1

Related Questions