Post storage for nodejs server with Ionic error Xmlhttprequest

Asked

Viewed 137 times

1

I’m using the ionic 3 to effect a requisition http post to a local server developed in node js but the error is occurring:

VM1515 ? ionicplatform=android:1 Xmlhttprequest cannot load http://localhost:3000/save. Response to preflight request doesn’t pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested Resource. Origin 'http://localhost:8100' is therefore not allowed access.

The request is called so:

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");
    }
});

}

Ja the function fnEnviaMenssagem is 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();
    });
});
  • Does this error only appear in the browser when you run Ionic serves or on the device as well? If in the browser I use a Chrome https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.