Ionic / Angular не подключается должным образом к nodeJS (маршруты отлично работают в почтальоне - PullRequest
0 голосов
/ 05 августа 2020

Я могу выполнять запросы GET и POST с помощью POSTMAN, и он работает. Я не могу понять, где я ошибаюсь в своем приложении. Мой запрос GET на тот же адрес работает нормально.

Например, в моем сервисе:

createOne(route, document) {
  console.log(`create new ${route}`, document);
  console.log(`http://localhost:8080/api/${route}`);
  return this.http.post(`http://localhost:8080/api/${route}`, document);
}

Это регистрируется в консоли как: Javascript Console Log

Unfortunately, it doesn't log a thing on the nodeJS server, so I'm sure I made a mistake somewhere in the server.js file - but can't figure out where!

POST request via postman to http://localhost:8080/api/appts with this for raw JSON body:

{
    "title": "test from postman",
    "description": "test description",
    "startTime": "2020-08-04T17:40:45.521-04:00",
    "endTime": "2020-08-04T20:10-04:00",
    "allDay": false
}

NodeJS Logs - request were done successfully from postman

My server.js file:

//1. require express and call it as a function
require('./api/data/db.js');
const cron = require('node-cron');
var express = require('express');
console.log(process.env.PORT);
var app = express();
var cors = require('cors');
var path = require('path');
var bodyParser = require('body-parser');
var routes = require('./api/routes');
var json2xls = require('json2xls');

//PORT SETUP
if (process.env.PORT) {
  app.use(cors());
  app.set('port', process.env.PORT || 8080);
} else {
  app.set('port', 8080);
}
// MIDDLEWARE
app.use(function (req, res, next) {
  console.log(req.method, req.url);
  next();
});
app.use(json2xls.middleware);

// ROUTING
app.use(express.static(path.join(__dirname, 'app/www'))); //setup primary route request folder
app.use('/node_modules', express.static(path.join(__dirname, 'node_modules')));
app.use(bodyParser.urlencoded({ extended: true })); //only get strings and arrays from form when false
app.use(bodyParser.json()); // tell backend to understand json data
app.use('/api', routes);
// LOAD THE SINGLE PAGE FOR IONIC
app.get('*', function (req, res) {
  res.sendFile('/app/www/index.html', { root: __dirname });
});

// START SERVER LISTENING
var server = app.listen(app.get('port'), function () {
  var port = server.address().port; // return the port for the server listening
  console.log('RayWood API running on port ' + port); //confirm app running
});

My File Tree is setup as follows: File Tree дерево файлов папки приложения, чтобы показать, где находится www folder при сборке

Видя, как сервер nodeJS не регистрирует URL или ЗАПРОС, я думаю, что проблема в моем сервере. js файл - но я все еще не знаю, что я сделал не так . Пожалуйста, помогите!

1 Ответ

0 голосов
/ 05 августа 2020

Вы не подписаны на Observable. Если вы не знакомы с Observable, вы можете преобразовать его в Promise, пожалуйста, используйте приведенный ниже пример реализации

createOne(route, document) {
      console.log(`create new ${route}`, document);
      console.log(`http://localhost:8080/api/${route}`);
    return new Promise((resolve, reject) => {
      
    
    this.http.post(`http://localhost:8080/api/${route}`,document).subscribe((resp)=>{
        console.log(resp);//This is the response from Node API
        resolve(resp);
    },(err)=>{
         reject(err)
    });
    
    });
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...