I want to make an app with ionic
and expressjs
, but I get this error:
This is the git of the project: https://github.com/hubmanS/GameStix
to raise the backend with nodemon server
and the frontend withionic server
I have this in app.js
the expressjs
.
var app = express();
const cors = require('cors');
app.use(cors());
app.options('*', cors());
var allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', 'http://localhost:8100');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
}
app.use(allowCrossDomain);
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
and from ionic
I want to call backend
.
constructor(public http: HttpClient) {
super(http);
this.http.get(`http://localhost:3000/customers/`);
console.log('MENSAJE', this.http.get(`http://localhost:3000/customers`));
}
You are supposed to enter this router
.
router.get('/customers', function(req, res, next) {
console.log('NOMAS');
res.render('index', { title: 'Express' });
});
but the console
.
The problem is both on the Client side and on the Server side.
SERVER
One of the recommendations I can make regarding the use of Express is that you always take into account the order in which you use the middleware functions that you pass to your server.
In your code I see that you have tried in many ways to solve the CORS problem .
The NPM package
cors
aims to solve many of the problems that arise when using cross domains in our applications.header()
Next, you try to use the Express method . This method is an alias ofset()
, which in turn is a method of the framework (Express).In Node we have
setHeader()
that it performs the same task asset()
.Now what's the difference? They both perform the same task: they set or write a
Header
to theResponse
. But, itsetHeader()
allows us to set only one key-value pair each time it is called, while it allows us to set more than one key-valueset()
pair in a single call.Example:
Wearing
set()
Wearing
header()
Wearing
setHeader()
Which one should we use? In principle, the one that suits our needs. Using the Express method allows us not to be so repetitive in writing our code.
Now when you set the following header:
You were not setting the header
Origin
.Reading the 'Access-Control-Allow-Headers' documentation , we see that it is used during a preflight request (request made to check if the CORS protocol is understood between the parties).
Among the headers that we can set are: 'Content-Type' , 'Accept' and 'X-Requested-With'.
The latter helps prevent certain types of attacks ( CSFR Mitigation ). You can read a little here about that topic.
Since we have options to choose from (use the package
cors
or set the headers manually), we must make a choice.One way you can have your Express Server setup is as follows: (without using the package
cors
)As you can see in the code, there are a few things that have moved around. In particular I must emphasize the order of the routes. The root path must always go at the end of existing paths.
CLIENT
On the client side there is not much that you have to adjust, but what you have to adjust is very important.
Based on what you uploaded to your repository, you have 1 serious problem.
In the file
customer.service.ts
you have the following line:The problem here is that
http
since it is an instance of the Angular ClassHttpClient
, it actually returns aObservable
, therefore in order to obtain the data of said request, we must subscribe to it.Since what you do is so simple (I think you're learning to use Angular) I won't go into detail about how to implement your service. But if I will tell you how you could use the module in this case.
The way to subscribe is as follows:
With this, the response of the request to the route
'/customers'
can be displayed by the console.Thus the CORS problem and the lack of response
http
must be corrected.You can read more about Angular in the guide .
As in other answers that I have given, I do NOT recommend modifying the server to make the applications work, especially in test environments such as a
ionic serve
, this command executes the application in your localhost and it is logical that the call does not work since they are made from different hosts. The app will work smoothly when you run it on a device. Inside the fileionic.config.json
you can add the following configuration:And each call you make instead of putting the full URL you just have to put the word you left in the property
path
If you don't want to do this configuration I recommend installing the Chrome extension to enable CORS while testing.
EDITION
I can see that you already have that configuration inside your project but you are not using it, in your file you have the
path
like/api
, make the call like this and it will work.