There's the code in my project which try to get an access token from wechat.
router.get('/', function(req, res, next) {
var params = new URLSearchParams({
grant_type: config.grantType,
appid: config.appID,
secret: config.appSecret
});
const url = config.wechat + '?' + params.toString();
http.get(url, (res) => {
console.log("haha");
console.log(res);
var rawData = '';
if (res.statusCode != 200) {
res.resume();
console.error('statusCode:' + res.statusCode);
return;
}
res.on('data', function (chunk) {
rawData += chunk; //buffer data if has
console.log(rawData);
});
res.on('end', function() {
try {
console.log("haha");
const accessTokenData = JSON.parse(rawData);
console.log("access: " + accessTokenData);
var newToken = new AccessToken({
token: accessTokenData["access_token"],
record_time: Date.now(),
expires: accessTokenData["expires_in"]
});
newToken.save(function(err) {
console.log("save error: " + err);
});
} catch (e) {
console.error('parse error: ' + e);
}
});
}).on('error', function(e) {
console.error("get access token failed: " + e);
});
console.log("sadfdas");
});
what I want to do is getting access token from the api and store it into mongodb using mongoose. when I start node service on my local vagrant machine and access the route, there is nothing printed on the terminal and new record inserted into mongodb. So I don't know where's the problem, I'm sure that the url is right, which I have tested with postman. Please help me find the problem. Any help will be appreciated.
Related
I have a two server(running on two different port), one is for chat application, and another is for API generation server(user should register by providing company
details,and my algorithm gives a API key to the user).
The problem is, i am checking the valid API key,provided by the user, if API key is true then it should redirect to chat server(port no 5200).
But it doesn't work, please give any idea to resolve this issues.
Here is my code,
`
app.post('/checkAPIkey',function(req,res){
var apikey=req.query.apikey;
var apikey1=uuidAPIkey.isAPIKey(apikey);
if(apikey1){
res.writeHead(302, {
Location: 'http://localhost:5200'
});
}else{
res.end("error");
}
});`
What you need is called Request Forwarding.
Example:
const http = require('http');
app.post('/checkAPIkey', function(req,res){
var apikey=req.query.apikey;
var apikey1 = uuidAPIkey.isAPIKey(apikey);
if(apikey1){
const options = {
port: NEW_PORT,
hostname: 'NEW_HOST',
method: 'POST',
path: '/'
};
var reqForward = http.request(options, (newResponse) => {
//Do something with your newResponse
var responseData = "";
newResponse.on('data', (chunk) => {
//Add data response from newResponse
responseData += chunk;
});
newResponse.on('end', () => {
//Nothing more, send it with your original Response
response.send(responseData);
});
});
// If ERROR
reqForward.on('error', (e) => {
console.error('Error: ' + e);
});
// Write to the request
reqForward.write(YOUR_POST_DATA);
reqForward.end();
} else {
res.end("error");
}
});
I am struggling from two days to do this operation but failure.In App.js i have tried:-
var express = require('express'),
app = express(),
httpServer = http.Server(app);
app.use(express.static(__dirname + '/data'));
app.get('./index',
function (req, res) {
res.render('index', {});
getUserInfo(req) //get your information to use it.
.then(function (userinfo) { //return your promise
res.json({ "name": userinfo.Name});
//you can declare/return more vars in this res.json.
//res.cookie('name', name); //https trouble
})
.error(function (e) {console.log("Error handler " + e)})
.catch(function (e) {console.log("Catch handler " + e)});
res.send('Hello World');
});
app.listen(8080);
My index.html code goes here
$.ajax({
url: '/index',
headers: {
Authorization: 'Bearer ' + idToken
},
processData: false,
}).done(function (data) {
localStorage.setItem('name', data.name);
//or whatever you want done.
}).fail(function (jqXHR, textStatus) {
var msg = 'Unable to fetch protected resource';
msg += '<br>' + jqXHR.status + ' ' + jqXHR.responseText;
if (jqXHR.status === 401) {
msg += '<br>Your token may be expired'
}
displayError(msg);
})
But unfortunately i get this error when i open index from local server:8080 :-
Cannot GET /
Try changing app.get('./index') to app.get('/index')
My Google Cloud Functions gets a URL from a database and then retrieves the source of the webpage in question using a GET request. I used Axios, Request, and native HTTP(S) modules.
Most websites work just fine and there is no problem whatsoever. Yet, for that URL https://www.healthline.com/health/food-nutrition/cricket-flour-nutrition, Axios and Request just hang forever until my Function times out, but with my native HTTPS tests, it downloads chunks from the url but never finishes, it then hangs until Function timeout.
My code is pretty simple...
const https = require('https');
const newAgent = new https.Agent({ keepAlive: true });
console.log('-> GET ', document.location.href);
const requestOptions = {
agent: newAgent,
hostname: document.location.hostname,
path: document.location.path
};
var fetchReq = https.request(requestOptions, (res) => {
let source = '';
console.log('STATUS: ' + res.statusCode);
Object.keys(res.headers).forEach(h => {
console.log('-> ' + h + ' -> ', JSON.stringify(res.headers[h]));
});
res.setEncoding('utf8');
res.on('data', (chunk) => {
console.log(`-----> CHUNK:`, chunk.substring(0, 40) + ' ... ', chunk.substring(chunk.length - 41, chunk.length - 1));
source += chunk;
});
res.on('close', () => {
console.log(`-----> CLOSED STREAM`);
});
res.on('end', () => {
console.log(`-----> STREAM ENDED`);
try {
console.log(`-> Fetched`, source.length);
console.log(`-> Saving to GCS`);
const bucket = storage.bucket(process.env.STORAGE_BUCKET_RAW);
const fileName = document.organization + '/' + document.key + '.raw';
const file = bucket.file(fileName);
const response = {
uri: 'gs://' + bucket.name + '/' + fileName,
data: preCleaning(source)
};
const options = {
gzip: true,
metadata: {
metadata: {
kind: document.kind,
organization: document.organization,
username: document.username,
key: document.key,
url: document.location.href
}
}
};
file.save(response.data, options)
.then(() => {
console.log(`-> Saved to GCS`);
resolve();
})
.catch(err => {
reject(new AppError(`Error saving raw document to storage (${uri}).`, 500, err));
});
} catch (e) {
console.log('HTTP message: ', e.message);
}
});
res.on('finish', () => {
console.log(`-----> FINISHED STREAM`);
});
res.on('error', (e) => {
console.log(`Got error: ${e.message}`);
})
}).on('socket', (socket) => {
socket.emit('agentRemove');
}).end();
I've tried different libraries, the same code works locally, it's just so confusing and I am running out of ideas...
I write API in order to client upload file. API has content-type multiple/form-data. But I don't know get values from client send to my
router.post('/upload/file', async (req, res) => {
var body = "";
try {
req.on('data', function (chunk) {
body += chunk;
});
req.on('end', function () {
console.log('body: ' + body);
var formData = new FormData(body);
console.log("=====================", formData.entries);
// var {accessTok, type, file} = req.params;
//
// if (!accessTok || !type || !file) {
res.json({
code: -1000,
message: 'Missing parameter(s). Please provide accessToken, type upload, file upload.'
});
res.end();
return null;
})
// }
}catch(err){
res.json({err: err.message});
res.end();
return;
}
I tried use FormData but not done. I get error is not function, formData.getKey('') is them same.
I have a larger process running through a large collection of locations/devices in an API response and I'm trying to get to individual devices and turn that into a response my target system will understand. However it seems my inline HTTP request is not firing.
I've tried moving the callback out of the 'end' event, but I'm not even getting the logging for earlier up in the function. The only logging output I get is the "getting status for zone xyz"
async.each(tempSystem.zones, function(zone, zoneCallback) {
var applianceDiscovered = {};
console.log("getting status for zone", zone);
var options = {
host: host,
path: '/webapi/' + zone.zoneId + '/status',
headers: {'Authorization' : 'Bearer ' + accessToken}
};
var req = https.get(options, function(res) {
if (res.statusCode != 200) {
console.log("error ", res.statusCode);
}
console.log(res);
var bodyChunks = [];
res.on('data', function(chunk) {
bodyChunks.push(chunk);
});
res.on('end', function() {
if (res.statusCode === 200) {
console.log("get zone status: ", res.statusCode);
var body = Buffer.concat(bodyChunks);
var zoneStatus = JSON.parse(body);
console.log(zoneStatus);
zoneCallback();
} else {
console.log(res.statusCode);
}
});
res.on('error', function(error) {
console.log(error);
});
});
req.on('error', function(e) {
console.log("error: ", e);
});
}, function(err){
console.log("finished with zones");
});