I am using ionic 3
to execute a http post
request for a local server developed in node js
but the error is occurring:
VM1515? ionicplatform = android: 1 XMLHttpRequest can not load link . Response to preflight request does not pass access control check: In 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ' link ' is therefore not allowed access.
The request is called this:
enviar(chat: Chat){
this.enviarMensagem.fnEnviarMensagem(chat).subscribe(data => {
this.response = data;
if(!this.response.status){
this.showAlert("ERROR!",this.response.menssagem);
}else{
alert("deu certo");
}
});
}
The fnEnviaMenssagem
function looks like this:
import { Injectable } from '@angular/core';
import { Http, Response, RequestOptions } from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
import {Observable} from 'rxjs/Observable'
import { AppModule } from '../app/app.module';
import { Chat } from '../models/chat';
@Injectable()
export class EnviarMensagem {
private url: string = AppModule.getUrl() + "/salvarMensagem";
constructor(private http: Http) {}
fnEnviarMensagem(chat: Chat){
// var data = {email: user.email, senha: user.senha};
return this.http.post(this.url, chat)
.do(this.logResponde)
.map(this.extractData)
.catch(this.catchError);
}
private catchError(error: Response | any){
console.log(error);
return Observable.throw(error.json().error || "Erro de conexão");
}
private logResponde(res: Response){
console.log(res);
}
private extractData(res: Response){
return res.json();
}
}
To receive in my index.js
I do so:
/* POST ONE customer. */
router.post('/salvarMensagem', function(req, res, next) {
var db = require('../db');
var Customer = db.Mongoose.model('customers', db.CustomerSchema, 'customers');
var newcustomer = new Customer({ name: req.body.name, email: req.body.email });
newcustomer.save(function(err) {
if (err) {
res.status(500).json({ error: err.message });
res.end();
return;
}
res.json(newcustomer);
res.end();
});
});