I have made a rest api for my ionic-2 android app but my http request cannot get data from my rest api service
I made a rest api with node.js and source code here
server.js
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({
extended:true
}));
app.use(bodyParser.json());
var port = process.env.PORT || 8080;
var router = express.Router();
router.get('/',function(req,res){
res.json({
"message":"hello world"
});
});
app.use('/api',router);
app.listen(port);
console.log("Listening Port");
package.json
{
"name": "node-api",
"main": "server.js",
"dependencies": {
"express": "~4.0.0",
"mongoose": "~3.6.13",
"body-parser": "~1.0.1"
}
}
I pushed on heroku service and its address here
my heroku rest api link
My ionic2 app from another directory here
home.ts
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import {Http} from '#angular/http';
import 'rxjs/add/operator/map';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
data:any;
constructor(public navCtrl: NavController,http:Http) {
http.get("https://appish.herokuapp.com/api")
.map((res) =>res.json())
.subscribe((data)=>{
this.data = JSON.stringify(data);
})
}
}
home.html
<ion-header>
<ion-navbar>
<ion-title>
Api
</ion-title>
</ion-navbar>
<ion-content padding>
{{data}}
</ion-content>
When I run this code with 'ionic serve' there is no error and no data but if I try other json sites to get data,it is running for example
i am trying ip.jsontest.com
I can get data
Where is the problem
Thank You
~
This looks like a CORS issue.
Try adding this to the beginning of your server.js and see if it resolves your issue.
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
If that doesn't work, you should take a look at the network tab in your browsers debugging tool. If you get a response and can see the data, it is an error in your ionic code. If you don't get any data, it's a problem with your server code or with the connection to the server.
Replaced server.js
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({
extended:true
}));
//answer is here..
app.use(function(req,res,next){
res.header("Access-Control-Allow-Origin","*");
res.header("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept");
next();
});
///
app.use(bodyParser.json());
var port = process.env.PORT || 8080;
var router = express.Router();
router.get('/',function(req,res){
res.json({
"message":"hello world"
});
});
app.use('/api',router);
app.listen(port);
console.log("Listening Port");
Related
I have a NestJS application that starts fine with:
npm start (npm run start:prod)
or
node dist/main
However, I want to use app.js and can't figure out how to configure the app.js file to accomplish this.
app.js file
var serverType = 'AM-API-MDD';
var express = require('express');
var http = require('http');
var path = require('path');
var bodyParser = require('body-parser');
var app = express();
var port = process.env.PORT || 3030;
app.use(function(req,res,next){
res.header("Access-Control-Allow-Origin","*");
res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, x-client-key, x-client-token, x-client-secret, Authorization");
next();
});
app.use(express.static(__dirname + '/dist/'));
//body parse
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ limit: '50mb',extended: true }))
// parse application/json
app.use(bodyParser.json({limit: '50mb', extended: true}))
app.all('/*', function(req, res, next) {
res.sendFile('dist/main.js', { root: __dirname });
});
// Handle 404
app.use(function(req, res) {
//res.send(‘404: Page not Found’, 404);
res.status(404).send({status:404, message: '404 Not Found', type:'client'});
});
// Handle 500
app.use(function(error, req, res, next) {
res.status(500).send({status:500, message: 'internal error', type:'internal'});
});
//listen
var httpServer = http.createServer(app);
httpServer.listen(port,() => console.log(serverType +' server running on port: '+ port));
trying to get app.js is the wrong approach.
node dist/main.js runs the application - so the startup script is the main.js file.
node-windows can reference the main.js file, rather than the app.js file.
Thanks to Jay McDoniel for pushing me in the right direction.
Hy, I try to get some data from a nodeJs API. I use react for frontend. I make my node API, I test with Postman and it work fine. When I use axios for get my data from the server I get a cors Error.
This is my axios call from react:
async function getMagazin(){
return (await axios.get(URL)).data;
}
And this is my node Js API:
import express from 'express';
import bodyParser from 'body-parser';
import db from './dbConfig.js';
import Magazin from './entities/Magazin.js';
import cors from 'cors';
let app = express();
let router = express.Router();
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use('/api', router);
app.use(cors());
app.use(function(req, res, next) {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
if ('OPTIONS' == req.method) {
res.sendStatus(200);
}
else {
next();
}});
async function getMagazin(){
return await Magazin.findAll();
}
router.route('/magazin').get(async (req, res) => {
res.json(await getMagazin());
})
let port = process.env.PORT || 8000;
app.listen(port);
console.log("API is running at " + port);
I try to add cors in my node API and hope the error is gone but not.
This is the error:
I try to make I debug, the api call go on the server and execute sql query, but when he return he give me that error. What I must add in my server side code for the API to work?
Switch the order so that cors is before api
app.use(cors());
app.use('/api', router);
When you use cors you have to indicate what domain or address can contact your api by adding it in the cors middleware like this:
app.use(cors({
origin: "http://localhost:3000"
}));
I've been banging my head against the wall on this one for a few hours. I'm not sure why it doesn't work but it's probably something simple I'm missing. It usually is...
Anyway, I'm doing a simple HTTP PUT from Angular 7 like this:
protected put(cmd: string, body: any) {
let headers = new HttpHeaders();
headers.append('Content-Type','application/json');
console.log(body);
return this._http.put(cmd, body, {headers: headers});
}
cmd and body are being passed in. I can see the body print out in the console and the cmd path is correct to hit my route path in Node.
From there, it comes into my Node/Express app. Which goes as follows:
'use strict';
const express = require('express');
const bodyParser = require('body-parser')
// Constants
const PORT = 8080;
const HOST = '0.0.0.0';
// App
const app = express();
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-
Type, Accept");
next();
});
app.use('/api', require('./routes/routes'));
app.use('/api/add-user', require('./routes/add-user/routes'));
app.listen(PORT, HOST);
console.log(`Running on http://${HOST}:${PORT}`);
And this is my routes file that console prints the empty body:
const express = require('express');
const router = express.Router();
const dvAdmin = require('../../controller/controller');
//Routes
//GETS
//PUTS
router.put('/addCCUser', function (req, res) {
console.log(req.body);
});
module.exports = router;
FE in react set up with create-react-app
BE in node
I deployed the app on heroku and all looks good but when I do a get to my BE I get a 404 (Not Found).
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var serveStatic = require('serve-static');
app = express();
app.use(bodyParser());
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
var port = process.env.PORT || 5000;
require('./server/routes')(app);
app.listen(port);
console.log('server started '+ port);
this is the route
module.exports = function (app) {
let apiUrlBase = "/api/v1";
app.get(`${apiUrlBase}/get-report/:_email`, (req, res) => {
const email = req.params._email;
axios.get(`https://www.beenverified.com/hk/dd/email?email=${email}`)
.then(response => {
let parserNames = utils.getNames(response.data);
let parserEmails = utils.getEmails(response.data);
let parserJobs = utils.getJobs(response.data);
let parserSocials = utils.getSocials(response.data);
let report = { "names": parserNames, "emails": parserEmails, "jobs": parserJobs, "socials": parserSocials };
res.json(report);
})
.catch(error => {
res.status(500).send('Internal Server Error');
});
})
}
Make sure your express app distinguishes both your api endpoint and your react app endpoint if you are serving both the api and the react app in one express instance. I ran into a similar problem. See Redux-Saga with babel/webpack "actions must be plain objects..." error in production but not dev
I am creating a simple socket io application. I followed all tutorials online to implement socket-io via Node JS. The current code worked only once and after connecting to the socket it got disconnected automatically. Since then I tried all PnC but it has not connected server side.
Can anyone please help me identify what stupidity I have done? Also I do not understand that whether it is client side problem or library problem.
package.json
{
"name": "IntellicarMaps",
"version": "1.0.0",
"description": "Demo app showing the use of Google Maps for Intellicar",
"main": "server.js",
"author": "Prateek",
"dependencies" : {
"express" : "~4.7.2",
"mongoose" : "~4.1.0",
"morgan" : "~1.2.2",
"body-parser": "~1.5.2",
"jsonwebtoken": "^5.0.2",
"method-override": "~2.1.2",
"socket.io": "~1.4.8"
}
}
server.js
// Dependencies
// -----------------------------------------------------
var express = require('express');
var mongoose = require('mongoose');
var port = process.env.PORT || 3000;
var database = require('./app/config');
var morgan = require('morgan');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var app = express();
var server = require('http').createServer(app);
global.io = require('socket.io').listen(server);
//------------------
// Express Configuration
// -----------------------------------------------------
// Sets the connection to MongoDB
mongoose.connect(database.localtest.url);
// Logging and Parsing
app.use(express.static(__dirname + '/public')); // sets the static files location to public
app.use('/bower_components', express.static(__dirname + '/bower_components')); // Use BowerComponents
app.use(morgan('dev')); // log with Morgan
app.use(bodyParser.json()); // parse application/json
app.use(bodyParser.urlencoded({extended: true})); // parse application/x-www-form-urlencoded
app.use(bodyParser.text()); // allows bodyParser to look at raw text
app.use(bodyParser.json({ type: 'application/vnd.api+json'})); // parse application/vnd.api+json as json
app.use(methodOverride());
//----------
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
// Routes
// ------------------------------------------------------
require('./app/routes.js')(app);
// Listen
// -------------------------------------------------------
//app.listen(port);
server.listen(port);
console.log('App listening on port ' + port);
//------------------------
// Socket io connection
//------------------------
io.on('connection', function(socket){
console.log('a user connected'); //this is not printing in console.
socket.emit('my other event', { my: 'data' });
//socket.on('disconnect', function(){
//console.log('user disconnected');
//});
});
io.emit('message',{"AlarmName":"CPU_FAN_DOWN"});
addForm.html(Client)
<script src="../lib/socket.io.js"></script>
<script>
var socket = io('http://localhost', {'force new connection': true});
socket.on('message', function (data) {
console.log(data);
});
</script>
socket.io.js in lib folder
this file is always loaded,i have checked in browser console