typescript can not get page - node.js

I have an app that uses instagram api and has two route index "/" and media "/". Index is working fine but media doesn't work. It doesn't enter in get method. I made them in the same wa but one is working and the other doesn't.
I'm using typescript and node.
And I cant find the error.
My media route:
import request from "request"
import express from "express"
import { Router } from 'express'
import { Post } from "../models/Post"
const app = express()
const token: any = process.env.INSTAGRAM_TOKEN
const mediaRouter = Router()
mediaRouter.get("/media", (req: any, res: any) => {
const url = 'https://graph.instagram.com/17841403377847296/media?fields=id,media_url,timestamp&access_token='+token+''
request({ url: url, json: true }, (error: string, response: any) => {
if(error){
res.send("unable to connect to service")
}else{
const array = response.body.data
var Posts: Post[] = [];
array.forEach(function (obj: any) {
Posts.push(new Post(obj.media_url, obj.timestamp))
})
res.send(Posts);
}
})
})
export default mediaRouter
my user "/" rout (that work)
import request from "request"
import express from "express"
import { Router } from 'express'
const app = express()
const token: any = process.env.INSTAGRAM_TOKEN
const userRouter = Router()
userRouter.get("/", (req: any, res: any) => {
const url = 'https://graph.instagram.com/17841403377847296/?access_token='+ token +'&fields=account_type,media_count,username'
request({ url: url, json: true }, (error: string, response: any) => {
if(error){
res.send("unable to connect to service")
}else{
res.send("USER " + response.body.username + " HAVE " + response.body.media_count + " POSTS")
}
})
})
export default userRouter
and my main app.ts
import express from "express"
import dotenv from "dotenv"
import userRouter from "./routes/userRouter";
import mediaRouter from "./routes/mediaRouter";
const app = express()
dotenv.config();
//envirements variable for port
const port: any = process.env.PORT
app.use("/media", mediaRouter)
app.use("/", userRouter)
//Adding server to port
app.listen(3000, () => {
console.log("server is listen on port "+ port +"")
})

Remove the "/media" path from mediaRouter. Since its declared twice, the resulting path will be GET /media/media instead of GET /media:
mediaRouter.get("/", (req: any, res: any) => {})

Related

calling mutli api in node express react

I am developing custom search engine when people search for somthing my search engine fetch all search engine api that I added and get results to my search engine , i am already added google custom search api now i need to add yahoo and goduckduck so how I can added other api and make my search engine fetch several api ?
const express = require('express');
const bodyParser = require('body-parser');
const logger = require('morgan');
const { SearchController } = require('./routes/search.js');
const { OutlineController } = require('./routes/outline.js');
const path = require('path');
const compression = require('compression');
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
const app = express();
app.use(compression());
app.use(express.static(path.resolve('../', 'build')));
app.use(bodyParser.text());
app.use(logger('dev'));
app.use('/search', SearchController);
app.use('/outline', OutlineController);
const port = process.env.PORT || 1337;
app.listen(port, () => {
console.log(`App listening on port ${port}`);
});
import * as express from 'express';
const { Router } = require('express');
const path = require('path');
const { get } = require('axios');
const router: express.Router = Router();
router.get('*', (req: express.Request, res: express.Response, next: express.NextFunction): void => {
res.sendFile(path.resolve('../', 'build/index.html'));
});
router.post('/:query/:start?', async (req: express.Request, res: express.Response) => {
const { query, start } = req.params;
try {
const { data: { items } } = await get(`
https://www.googleapis.com/customsearch/v1?key=AIzaSyBexWro6lOuVcfmR5uSFvd-jVY8uee45OA&cx=000950167190857528722:vf0rypkbf0w&start=${start
? start
: 10}&q=${encodeURI(query)}`);
console.log('this');
res.send(items);
} catch (error) {
console.error(error);
}
});
export const SearchController = router;
const { Request, Response, Router } = require('express');
import * as express from 'express';
const request = require('request');
const unfluff = require('unfluff');
const router: any = Router();
router.post('/:site(*)', (req: express.Request, response: express.Response) => {
const site = req.params.site;
request(site, (err: Error, res: any, body: any) => {
const data = unfluff(body);
response.send({
title: data.title,
text: data.text
});
});
});
export const OutlineController = router;

typescript application routes

I make simple instagram api application and I have problem with my routes, export and import. i get error TypeError: Router.use() requires a middleware function but got a undefined
at Function.use (C:\Documents\Desktop\digi.me\node_modules\express\lib\router\index.js:458:13)
at Object. (C:\Documents\Desktop\digi.me\lib\routes\routes.js:12:8)
I have two routes userRouter that go on localhost:3000
and mediaRouter that go on localhost:3000/media
my userRouter.ts
import request, { post } from "request"
import express from "express"
import { Router } from 'express';
const app = express()
const token: any = process.env.INSTAGRAM_TOKEN
export const userRouter = Router()
userRouter.get("/", (req: any, res: any) => {
const url = 'https://graph.instagram.com/17841403377847296/?access_token='+token+'&fields=account_type,media_count,username'
request({ url: url, json: true }, (error: string, response: any) => {
if(error){
res.send("unable to connect to service")
}else{
res.send("USER " + response.body.username + " HAVE " + response.body.media_count + " POSTS")
}
})
})
my mediaRouter
import request, { post } from "request"
import express from "express"
import {Post} from "../models/Post"
import { Router } from 'express';
const token: any = process.env.INSTAGRAM_TOKEN
export const mediaRouter = Router()
mediaRouter.get("/media", (req: any, res: any) => {
console.log(0);
const url = 'https://graph.instagram.com/17841403377847296/media?fields=id,media_url,timestamp&access_token='+token+''
request({ url: url, json: true }, (error:string, response: any) => {
if(error){
console.log('error');
res.send("unable to connect to service")
} else {
const array = response.body.data
var Posts: Post[] = [];
array.forEach(function (obj: any) {
Posts.push(new Post(obj.media_url, obj.timestamp))
});
res.send(Posts);
}
})
})
my routes.ts
import { Router } from 'express';
import userRouter from "./routes"
import mediaRouter from "./routes"
import express from 'express';
const app = express();
const routes = Router();
routes.use('/', userRouter);
routes.use('/media', mediaRouter);
export default routes
and my main app.ts
import express from "express"
import * as dotenv from "dotenv"
import routes from "./routes/routes"
const app = express()
dotenv.config();
//envirements variable for port
const port: any = process.env.PORT
app.use(routes);
app.use(express.json());
//Adding server to port
app.listen(port, () => {
console.log("server is listen on port 3000")
})

How do I redirect in nodejs express with different request body

i am making the webside , here is some of my code
in app.ts
import * as express from 'express';
import knex from './init/knex';
// Router
import indexRouter from './routers/index-router';
// Service
import gameService from './service/game-service';
const app = express();
var server = app.listen(8080, () => {
console.log('listen to 8080');
})
app.use('/', new indexRouter(new gameService(knex)).router());
in index-router.ts
import * as express from 'express';
export default class indexRouter {
private gameService: any;
constructor(gameService: any) {
this.gameService = gameService;
}
router() {
let router = express.Router();
router.get("/", this.get.bind(this));
router.post("/test", this.test.bind(this));
return router;
}
test(req: any, res: any) {
// console.log("indexRouter get()");
console.log(req.body);
res.render("gameboard", { pin: "1", username: "1", player: 1 });
}
get(req: any, res: any, next:any) {
req.body = {3:"3"};
// something i want to do here
}
}
When user link to "http://localhost:8080/" and "get" method is called
How can i change:
the url from "http://localhost:8080/" to "http://localhost:8080/test"
call "test" method with the new request body
I have spent a lot of time google how to do i but i can't find the best way to do the above two things.
Do you mean something like:
get(req: any, res: any, next:any) {
test(req.body);
res.redirect('/test');
}
?

The response is showing as buffer in the node server

I have created a simple react app. The problem which I'm finding is when I'm hitting the url, in the response, it is showing as buffer, which should not be the case.
My code
index.js
import axios from 'axios';
export const ADD_CART = "ADD_CART";
export const REMOVE_CART = "REMOVE_CART";
export const LOGIN = "LOGIN";
export const BASE_API_URL = "http://localhost:3030";
export function addToCart(item) {
console.log(window.localStorage.getItem('WCToken'))
console.log(window.localStorage.getItem('WCTrustedToken'))
var headers = {
'Content-Type': 'application/json',
'WCToken': window.localStorage.getItem('WCToken'),
'WCTrustedToken': window.localStorage.getItem('WCTrustedToken')
}
axios.post(BASE_API_URL + "/cart", {
orderItem: [
{
productId: item.uniqueID, //working for 12262
quantity: '1'
}
]
}, {headers: headers}).then(res => console.log(res))
.catch(err => console.log(err));
return {
type: ADD_CART,
payload: item
};
}
export function removeFromCart(cartList, id) {
return {
type: REMOVE_CART,
payload: cartList.filter(i => i.uniqueID != id)
};
}
export const login = () => {
return axios.post(BASE_API_URL + "/guestidentity", {}).then(res => {
window.localStorage.setItem("WCToken", res.data.express.WCToken)
window.localStorage.setItem("WCTrustedToken", res.data.express.WCTrustedToken)
return {
type: LOGIN,
payload: {}
}
}).catch(e => {
console.log(e);
return {
type: LOGIN,
payload: {}
}
});
};
server.js
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const Client = require('node-rest-client').Client;//import it here
const app = express();
const helmet = require('helmet');
const morgan = require('morgan');
// enhance your app security with Helmet
app.use(helmet());
// use bodyParser to parse application/json content-type
app.use(bodyParser.json());
// log HTTP requests
app.use(morgan('combined'));
app.use(cors());
process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = 0
app.post('/guestidentity',(req, res) => {
console.log("Hello from Server")
var client = new Client();
// direct way
client.post("https://149.129.128.3:5443/wcs/resources/store/1/guestidentity", (data, response) => {
res.send({ express: data });
});
});
app.post('/cart',(req, res) => {
console.log("Hello from Server")
var client = new Client();
// direct way
client.post("https://149.129.128.3:5443/wcs/resources/store/1/cart", (data, response) => {
res.send({ express: data });
});
});
const port = 3030;
app.listen(port, () => console.log(`Server running on port ${port}`));
I dont know where my code is getting wrong and why buffer is showing in response. Can somebody please guide me on this. Or provide me an insight how to troubleshoot this issue.
You are sending to the client an object with the form:
{
express: data
}
And when you log that on the console you see that data is an object:
{
data: [],
type: "buffer"
}
Which means that your post request inside express is returning that object.

Response is showing as buffer in reactjs app

I have created a simple react app. The problem which I'm finding is when I'm hitting the url, in the response, it is showing as buffer, which should not be the case.
My code
index.js
import axios from 'axios';
export const ADD_CART = "ADD_CART";
export const REMOVE_CART = "REMOVE_CART";
export const LOGIN = "LOGIN";
export const BASE_API_URL = "http://localhost:3030";
export function addToCart(item) {
console.log(window.localStorage.getItem('WCToken'))
console.log(window.localStorage.getItem('WCTrustedToken'))
var headers = {
'Content-Type': 'application/json',
'WCToken': window.localStorage.getItem('WCToken'),
'WCTrustedToken': window.localStorage.getItem('WCTrustedToken')
}
axios.post(BASE_API_URL + "/cart", {
orderItem: [
{
productId: item.uniqueID, //working for 12262
quantity: '1'
}
]
}, {headers: headers}).then(res => console.log(res))
.catch(err => console.log(err));
return {
type: ADD_CART,
payload: item
};
}
export function removeFromCart(cartList, id) {
return {
type: REMOVE_CART,
payload: cartList.filter(i => i.uniqueID != id)
};
}
export const login = () => {
return axios.post(BASE_API_URL + "/guestidentity", {}).then(res => {
window.localStorage.setItem("WCToken", res.data.express.WCToken)
window.localStorage.setItem("WCTrustedToken", res.data.express.WCTrustedToken)
return {
type: LOGIN,
payload: {}
}
}).catch(e => {
console.log(e);
return {
type: LOGIN,
payload: {}
}
});
};
server.js
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const Client = require('node-rest-client').Client;//import it here
const app = express();
const helmet = require('helmet');
const morgan = require('morgan');
// enhance your app security with Helmet
app.use(helmet());
// use bodyParser to parse application/json content-type
app.use(bodyParser.json());
// log HTTP requests
app.use(morgan('combined'));
app.use(cors());
process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = 0
app.post('/guestidentity',(req, res) => {
console.log("Hello from Server")
var client = new Client();
// direct way
client.post("https://149.129.128.3:5443/wcs/resources/store/1/guestidentity", (data, response) => {
res.send({ express: data });
});
});
app.post('/cart',(req, res) => {
console.log("Hello from Server")
var client = new Client();
// direct way
client.post("https://149.129.128.3:5443/wcs/resources/store/1/cart", (data, response) => {
res.send({ express: data });
});
});
const port = 3030;
app.listen(port, () => console.log(`Server running on port ${port}`));
I dont know where my code is getting wrong and why buffer is showing in response. Can somebody please guide me on this. Or provide me an insight how to troubleshoot this issue.
You might need to config your client as to parse response as JSON.
var options = {
mimetypes: {
json: ["application/json", "application/my-custom-content-type-for-json;charset=utf-8"]
}
};
var client = new Client(options);

Resources