Search code examples
node.jsapihapi.jsadmin-on-rest

Admin-on-rest Cross-Domain Requests on localhost port


I'm using Hapijs (Version 17.2.3) for developing API. In the frontend, I used Admin-on-rest framework. Hapijs API is running at http://localhost:3000 and Admin-on-rest is running at http://localhost:3001.

To display users list send a request to http://localhost:3000/api/users in Admin-on-rest panel. Then I get the error in the Chrome console:

Failed to load http://localhost:3000/api/users?filter=%7B%7D&range=%5B0%2C9%5D&sort=%5B%22id%22%2C%22DESC%22%5D: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.

enter image description here

To fix this problem, I searched a lot, but the problem did not resolve, and I did not find the reason for it. How to solved problem!?

My config for Hapijs server is:

'use strict';

const Hapi = require('hapi');
const Boom = require('boom');
const glob = require('glob');
const path = require('path');
const Config = require('./config');
const { Model } = require('objection');
const Knex = require('knex');
const KnexConfig = require('./knexfile');

// Initialize knex.
const knex = Knex(KnexConfig);

// Bind all Models to a knex instance. If you only have one database in
// your server this is all you have to do. For multi database systems, see
// the Model.bindKnex method.
Model.knex(knex);

// The connection object takes some
// configuration, including the port
const server = Hapi.server({
    port: Config.server.port,
    host: Config.server.host,
    routes: {
        cors: {
            origin: ['*'],
            credentials: true,
            additionalHeaders: ['headers', 'x-csrf-token', 'authorization', 'content-type']
        }
    }
});

const init = async () => {
    await server.start();
    console.log(`Server running at: ${server.info.uri}`);
};
process.on('unhandledRejection', (err) => {
    console.log(err);
    process.exit(1);
});

// Look through the routes in
// all the subdirectories of API
// and create a new route for each
glob
.sync('api/**/routes/*.js', {
    root: __dirname
})
.forEach(file => {
    const route = require(path.join(__dirname, file));
    server.route(route);
});

// Start the server
init();

My App.js config for Admin-on-rest is:

import React from 'react';
import { jsonServerRestClient, Admin, Resource, Delete, fetchUtils, simpleRestClient  } from 'admin-on-rest';
import PostIcon from 'material-ui/svg-icons/action/book';
import UserIcon from 'material-ui/svg-icons/social/group';
import VideoIcon from 'material-ui/svg-icons/social/group';
import farsiMessages from 'aor-language-farsi';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import './index.css';

import { PostList, PostEdit, PostCreate } from './Posts';
import { VideoList } from './Videos';
import { UserList, UserCreate, UserEdit } from './Users';
import Dashboard from './Dashboard';
import authClient from './authClient';

// Set Farsi messages
const messages = {
    'fa': farsiMessages,
};

// Customize Theme
const myTheme = {
    isRtl: true,
    fontFamily: 'IRANSans'
};

const httpClient = (url, options = {}) => {
    if (!options.headers) {
        options.headers = new Headers({ Accept: 'application/json' });
    }
    return fetchUtils.fetchJson(url, options);
}

const App = () => (
    <Admin 
    theme={getMuiTheme(myTheme)} 
    authClient={authClient} 
    dashboard={Dashboard} 
    locale="fa" messages={messages} 
    restClient={simpleRestClient('http://localhost:3000/api', httpClient)}>
        <Resource name="posts" list={PostList} edit={PostEdit} create={PostCreate} remove={Delete} icon={PostIcon}  />
        <Resource name="videos" list={VideoList} icon={VideoIcon}  />
        <Resource edit={UserEdit} create={UserCreate} name="users" list={UserList} icon={UserIcon} />
    </Admin>
);

export default App;

Solution

  • have you tried this... it might fix the issue

    const server = Hapi.server({
        port: Config.server.port,
        host: Config.server.host,
        routes: {
            cors: true
        }
    });