Node Post API не звонит с ангулярного сервиса - PullRequest
0 голосов
/ 02 мая 2018

Я пытался вызвать post API, но я не могу вызвать его, на самом деле, API Get легко вызывается, но не работает с методом POST

Ниже мой код server.js

path = require('path'),
express = require('express'),
app = express(),
port = process.env.PORT || 5010,
bodyParser = require('body-parser'),
sql = require("mssql");
//  cors = require('cors')

 config =  {
  server:'MSSQLSERVER2012',
   database:"Test",
   user:"sa",
   password:"tat123",

};


app.use(express.static(path.join(__dirname, 'app')));
app.use(bodyParser.urlencoded( {extended:true }));
app.use(bodyParser.json());

// headers and content type
app.use(function (req, res, next) {
//set headers to allow cross origin request.
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});

app.get('/country', function (req, res) {
  sql.connect(config).then(function () {
      var request = new sql.Request();
      request.query("select * from Table_1").then(function (recordSet) {
          //console.log(recordSet);
          res.send(recordSet['recordset']);
          sql.close();
      }).catch(function (err) {
        //8.
        console.log(err);
        sql.close();
    });
  }).catch(function (err) {
    //9.
    console.log(err);
});
});

app.post('/country2', function (req, res) {
  sql.connect(config).then(function () {
      var request = new sql.Request();
      request.query("select * from Table_1").then(function (recordSet) {
          //console.log(recordSet);
          res.send(recordSet['recordset']);
          sql.close();
      }).catch(function (err) {
        //8.
        console.log(err);
        sql.close();
    });
  }).catch(function (err) {
    //9.
    console.log(err);
});
});

app.use(function (req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
  });

  app.use(function (req, res, next) {
    var err = new Error('Not Found1');
    console.log(err);
    err.status = 500;
    next(err);
    });

  // error handlers
  app.use(function (err, req, res, next) {
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development'?err: {};
  res.status(err.status || 500);
  res.json( {error:err });
  });

var server = app.listen(port, function () {
console.log('Node RESTful API server started on: ' + port);
});

module.exports = app;

и ниже мой угловой сервис, который вызывает почтовый метод

import {Injectable }from '@angular/core';
import {Observable}from 'rxjs/Observable';
import {of }from 'rxjs/observable/of';
import {Http, Response, Request, RequestOptions, RequestMethod,Headers}from '@angular/http';
import {Country}from './Countries';
import {}from ''
import 'rxjs/add/operator/map';
import * as express from 'express'
import {HttpHeaders }from '@angular/common/http';

@Injectable()
export class CountryServiceService {
options:any = null;

aryCountry:Country[] = [];
constructor(public http:Http) {
this.options = ( {

headers:new Headers( {
'Content-Type':'application/json; charset=utf-8', // Format set to JSON
//'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
})
});

}

SelectData():any {

return this.http.get('http://localhost:5010/country',this.options).map(response => {
return response.json();
});


}

SelectDataPost():any{
  debugger;
   return this.http.post('http://127.0.0.1:5010/country2',null,this.options)
    .map(data => {
       return data.json();
    });
}

}

Вызов этого метода выглядит как

this.countryservice.SelectDataPost().subscribe(country=>{

this.countries=country  });

Когда я вызываю метод get, я легко могу получить данные, но когда я пытаюсь сделать то же самое с методом post, я не могу получить его

P.S Я использую

угловой CLI: 1.6,7 Узел: 7.10.0 ОС: win32 x64 Угловая: 5.2,9

Когда я запускаю этот URL-адрес в Почтальоне, чтобы проверить правильность этого API, он показывает мне результат

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...