Can make post request to localhost using node-fetch, but unable to do so using Axios - axios

I have tried making the same post request using node-fetch and axios.
var fetch = require('node-fetch');
var axios = require('axios');
async function fetchTest(host, port, body) {
const response = {
successMessage: '',
errorMessage: ''
}
try {
const streamResponse = await fetch(`${host}:${port}`, {
method: 'post',
body: JSON.stringify(body)
})
const jsonResponse = await streamResponse.json()
response.successMessage = jsonResponse;
} catch (error) {
response.errorMessage = error;
}
return response;
}
async function axiosTest(host, port, body) {
const response = {
successMessage: '',
errorMessage: ''
}
try {
const jsonResponse = await axios({
method: 'post',
url: `${host}:${port}`,
data: body
})
response.successMessage = jsonResponse;
} catch (error) {
response.errorMessage = error;
}
return response;
}
async function test() {
console.log(await fetchTest('http://127.0.0.1', '8801', { type: 'request', cmd: 'devices' }));
console.log(await axiosTest('http://127.0.0.1', '8801', { type: 'request', cmd: 'devices' }));
}
test();
The request made with node-fetch works nicely. The request made with axios returns (IP address redacted with ...) an error:
{ successMessage: '',
errorMessage:
{ Error: connect ECONNREFUSED ...:80
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1161:14)
errno: 'ECONNREFUSED',
code: 'ECONNREFUSED',
syscall: 'connect',
address: '...',
port: 80,
config:
{ adapter: [Function: httpAdapter],
transformRequest: [Object],
transformResponse: [Object],
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
validateStatus: [Function: validateStatus],
headers: [Object],
method: 'post',
url: 'http://127.0.0.1:8801',
data: '{"type":"request","cmd":"devices"}' },
request:
Writable {
_writableState: [WritableState],
writable: true,
_events: [Object],
_eventsCount: 2,
_maxListeners: undefined,
_options: [Object],
_redirectCount: 1,
_redirects: [],
_requestBodyLength: 39,
_requestBodyBuffers: [],
_onNativeResponse: [Function],
_currentRequest: [ClientRequest],
_currentUrl: 'http://.../',
_isRedirect: true },
response: undefined } }
What might be the reason? Am I doing something wrong?
EDITED with more info requested in comment:
The axios request fails the same way if I comment out the node-fetch request.
The node-fetch request returns:
{
cmd: 'devices',
payload: { devices: [Array] },
type: 'response' },
}
Since I wrap the result in a response object, the console.log looks like
{
successMessage:
{
cmd: 'devices',
payload: { devices: [Array] },
type: 'response'
},
errorMessage: ''
}

Related

can't create cesium ion assets with from parameter

When I create an assets in cesium ion, I can not make it work if I use the from parameter.
this code is working, it create the assets and send back infos about the upload location.
axios.post('https://api.cesium.com/v1/assets', {
name: selectedFile.name,
description: '',
type: '3DTILES',
options: {
position:[ 2.29, 48.85, 0.1],
sourceType: srcType
}
},{
headers: { Authorization: `Bearer ${accessToken}` }
})
.then(response => assetCreated(response))
.catch(function (error) {
console.log(error);
});
But If I add the from parameter like this :
axios.post('https://api.cesium.com/v1/assets', {
name: selectedFile.name,
description: '',
type: '3DTILES',
options: {
position:[ 2.29, 48.85, 0.1],
sourceType: srcType
},
from: {
type:'S3',
bucket: 'mybucket',
credentials :{
accessKey:'key',
secretAccessKey:'secretkey'
}
}
},{
headers: { Authorization: `Bearer ${accessToken}` }
})
.then(response => assetCreated(response))
.catch(function (error) {
console.log(error);
});
Then I get "Request failed with status code 400".
From what I understand from the documentation (https://cesium.com/learn/ion/rest-api/#operation/postAssets) this should work though.
What am I doing wrong ?
Thanks for the help.

google People API error code: 400, Invalid JSON payload received

Hi guys am working on a projet the uses google people API to do crud operation on an authentiated user using nodejs and express server.
I was able to get all contacts, search for a particular contact and using the resoureName.
but i'm unable to create contact group or label. i have read google documentation for weeks, i am having error
here isresponse from the server
^
GaxiosError: Invalid JSON payload received. Unknown name "contactGroup[name]": Cannot bind query parameter. Field 'contactGroup[name]' could not be found in request message. at Gaxios. (D:#001ADeveloperZone\workSpaces\autmarket\node_modules\gaxios\build\src\gaxios.js:73:27)
at Generator.next ()
at fulfilled (D:#001ADeveloperZone\workSpaces\autmarket\node_modules\gaxios\build\src\gaxios.js:16:58)
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
response: {
config: {
access_token: ',
refresh_token: '',
url: 'https://people.googleapis.com/v1/contactGroups?contactGroup%5Bname%5D=hotmail',
method: 'POST',
paramsSerializer: [Function (anonymous)],
headers: {
'Accept-Encoding': 'gzip',
'User-Agent': 'google-api-nodejs-client/0.7.2 (gzip)',
Authorization: '',
Accept: 'application/json'
},
params: [Object: null prototype] { contactGroup: { name: 'hotmail' } },
validateStatus: [Function (anonymous)],
responseType: 'json'
},
data: {
error: {
code: 400,
message: Invalid JSON payload received. Unknown name "contactGroup[name]": Cannot bind query parameter. Field 'contactGroup[name]' could not be found in request message.,
errors: [
{
message: Invalid JSON payload received. Unknown name "contactGroup[name]": Cannot bind query parameter. Field 'contactGroup[name]' could not be found in request message.,
reason: 'invalid'
}
],
status: 'INVALID_ARGUMENT',
details: [
{
'#type': 'type.googleapis.com/google.rpc.BadRequest',
fieldViolations: [Array]
}
]
}
},
headers: {
'alt-svc': 'h3=":443"; ma=2592000,h3-29=":443"; ma=2592000,h3-Q050=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000,quic=":443"; ma=2592000; v="46,43"',
'cache-control': 'private',
connection: 'close',
'content-encoding': 'gzip',
'content-type': 'application/json; charset=UTF-8',
date: 'Tue, 08 Mar 2022 16:27:38 GMT',
server: 'ESF',
'transfer-encoding': 'chunked',
vary: 'Origin, X-Origin, Referer',
'x-content-type-options': 'nosniff',
'x-frame-options': 'SAMEORIGIN',
'x-xss-protection': '0'
},
status: 400,
statusText: 'Bad Request'
},
config: {
access_token: ,
refresh_token: '',
url: 'https://people.googleapis.com/v1/contactGroups?contactGroup%5Bname%5D=hotmail',
method: 'POST',
paramsSerializer: [Function (anonymous)],
headers: {
'Accept-Encoding': 'gzip',
'User-Agent': 'google-api-nodejs-client/0.7.2 (gzip)',
Authorization: '',
Accept: 'application/json'
},
params: [Object: null prototype] { contactGroup: { name: 'hotmail' } },
validateStatus: [Function (anonymous)],
responseType: 'json'
},
code: 400,
errors: [
{
message: Invalid JSON payload received. Unknown name "contactGroup[name]": Cannot bind query parameter. Field 'contactGroup[name]' could not be found in request message.,
reason: 'invalid'
}
]
}
here is my code
create_group: (req, res) => {
try {
//create group or label
let userGoogleContactsGroups = getGroups().then((data) =>
JSON.parse(JSON.stringify(data))
);
let userGroups = userGoogleContactsGroups.then(({ contactGroups }) => {
let names = contactGroups.map((group) => `${group.name}`);
return names;
});
userGroups.then((data) => {
if (data.includes("amazoggn")) {
return res.status(301).json({ code: 301, mesage: "group exist" });
} else {
// let name =" amazoggn";
try {
contactGroup={
name:name
}
let strdata = JSON.parse(JSON.stringify({contactGroup}));
let mydata = people.contactGroups.create(strdata)
if (mydata) {
console.log(mydata)
} else {
return "error occured"
}
} catch (error) {
console.log(error)
}
}
});
} catch (error) {
console.log(error);
}
}
please I need help on this how do you create contact group in google people api
Looking at the docs I think you should specify a field requestBody in the call to people.contactGroups.create.
Try something like this:
const res = await people.contactGroups.create({
requestBody: {
"contactGroup": {
"name": "HelloWorld"
}
}
});

Why my mongoose request returns a query but not result data, user information in, in my case? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I don't know why it doesn't work for me now, but it did work earlier.
I need to retrieve information from my db. I can easily save data using Model.create but when I want to get data I get:
Query {
_mongooseOptions: {},
_transforms: [],
_hooks: Kareem { _pres: Map {}, _posts: Map {} },
_executionCount: 0,
mongooseCollection: NativeCollection {
collection: Collection { s: [Object] },
Promise: [Function: Promise],
opts: {
bufferCommands: true,
capped: false,
Promise: [Function: Promise],
'$wasForceClosed': undefined
},
name: 'users',
collectionName: 'users',
conn: NativeConnection {
base: [Mongoose],
collections: [Object],
models: [Object],
config: [Object],
replica: false,
options: null,
otherDbs: [],
relatedDbs: {},
states: [Object],
_readyState: 1,
_closeCalled: false,
_hasOpened: true,
plugins: [],
_listening: false,
_connectionOptions: [Object],
client: [MongoClient],
'$initialConnection': [Promise],
_events: [Object: null prototype] {},
_eventsCount: 0,
name: 'test_name',
host: 'cocoondb-shard-00-02-qx9lu.mongodb.net',
port: 27017,
user: 'test',
pass: '1234',
db: [Db]
},
...
I have only one route and use graphql apollo server.
my express route is:
server.js (main file - enterpoint)
import confirmRoute from '../src/routes/confirm';
const app = express();
app.use('/confirm', confirmRoute);
confirm.js
import { Router } from 'express';
import SimpleCrypto from 'simple-crypto-js';
import { env } from '../../environment';
import { User } from '../models/user.model';
const secret = env.TOKEN_SECRET;
const router = Router();
router.get('/*', (req, res) => {
const crypter = new SimpleCrypto(secret);
const id = crypter.decrypt(req.url.slice(1));
const user = User.find({ id }, callback => callback);
res.status(200).send(`Hello, your email confirmed successfully : ${id}`);
})
module.exports = router;
schema
import { Schema, model } from 'mongoose';
const userSchema = new Schema({
firstname: { type: String, required: [false, 'firstname address required'] },
lastname: { type: String, required: [false, 'lastname address required'] },
email: { type: String, required: [true, 'email address required'] },
password: { type: String, required: [true, 'password required'] },
confirmed: { type: Boolean, default: false },
instagram: { type: String, default: "" },
facebook: { type: String, default: "" },
role: { type: String }
}, { timestamps: true });
export const User = model('user', userSchema, 'users');
What am I doing wrong here?
I apologise if my question is silly...
It seems you are not actually executing the query.
Please try one of this solutions to make it work.
Also I used findById, but it does not matter, you can continue to query with findOne also.
Alternative 1: then catch blocks:
router.get("/users/:id", (req, res) => {
User.findById(req.params.id)
.then(doc => {
res.send(doc);
})
.catch(err => {
console.log(err);
return res.status(500).send("something went wrong");
});
});
Alternative 2: callback
router.get("/users/:id", (req, res) => {
User.findById(req.params.id, (err, doc) => {
if (err) {
console.log(err);
return res.status(500).send("something went wrong");
}
return res.send(doc);
});
});
Alternative 3: async/await
router.get("/users/:id", async (req, res) => {
try {
let result = await User.findById(req.params.id);
res.send(result);
} catch (err) {
console.log(err);
return res.status(500).send("something went wrong");
}
});
To apply your case:
router.get("/*", (req, res) => {
const crypter = new SimpleCrypto(secret);
const id = crypter.decrypt(req.url.slice(1));
console.log("id: ", id);
User.findById(req.params.id)
.then(doc => {
console.log("doc: ", doc);
res.status(200).send(`Hello, your email confirmed successfully : ${id}`);
})
.catch(err => {
console.log(err);
return res.status(500).send("something went wrong");
});
});

Unable to receive email address in sailsjs from passportjs

I'm unable to get the email address from facebook when i'm making the following call...
// https://developers.facebook.com/docs/
// https://developers.facebook.com/docs/reference/login/
facebook: function(req, res) {
passport.authenticate('facebook', { scope : ['email'] }, function(err, user) {
req.logIn(user, function(err) {
if (err) {
return;
}
res.redirect('/');
return;
});
})(req, res);
},
This is how the response is handled and is basically the PassportJS docs code.
customMiddleware: function(app) {
passport.use(new FacebookStrategy({
clientID: "5xxxxxxxxxxxxx6",
clientSecret: "exxxxxxxxxxxxxxxxxxxxxxxxxxxd9",
callbackURL: "http://localhost:1337/auth/facebook/callback"
}, verifyHandler));
app.use(passport.initialize());
app.use(passport.session());
}
And here is the handler.
var passport = require('passport')
, FacebookStrategy = require('passport-facebook').Strategy;
var verifyHandler = function(token, tokenSecret, profile, done) {
process.nextTick(function() {
sails.log.info(profile);
Serviceseeker.findOne({uid: profile.id}, function(err, serviceseeker) {
if (serviceseeker) {
return done(null, serviceseeker);
}
else {
var data = {
provider: profile.provider,
uid: profile.id,
name: profile.displayName
};
if (profile.emails && profile.emails[0] && profile.emails[0].value) {
data.email = profile.emails[0].value;
}
if (profile.name && profile.name.givenName) {
data.firstName = profile.name.givenName;
}
if (profile.name && profile.name.familyName) {
data.lastName = profile.name.familyName;
}
Serviceseeker.create(data, function(err, serviceseeker) {
return done(err, serviceseeker);
});
}
});
});
};
And this is the response that I'm getting
info: info: { id: '1xxxxxxxxxxxxxx9',
username: undefined,
displayName: 'Txxxx Slxxxxn',
name:
{ familyName: undefined,
givenName: undefined,
middleName: undefined },
gender: undefined,
profileUrl: undefined,
provider: 'facebook',
_raw: '{"name":"Txxxx Slxxxxn","id":"1xxxxxxxxxxxxxx9"}',
_json: { name: 'Txxxx Slxxxxn', id: '1xxxxxxxxxxxxxx9' } }
Did you try:
passport.use(new FacebookStrategy({
clientID: 'CLIENT_ID',
clientSecret: 'CLIENT_SECRET',
callbackURL: "http://www.example.com/auth/facebook/callback"
passReqToCallback : true,
profileFields: ['id', 'emails', 'name'] //This
},

OrientDB Server Error

I have a Problem with the orientjs Driver (https://github.com/orientechnologies/orientjs) or my OrientDB (v2.1.15). I have a Node.js Server and open a Connection to the Database Server like this:
var OrientDB = require('orientjs');
var orientserver = OrientDB({
host: 'localhost',
port: 2424,
username: 'root',
password: 'Orientdb'
});
Next I open a Database Connection and work with this DB, all works fine to this point. But if I want to list all Databases with the orientserver.list() Method I get this Error:
Unhandled rejection OrientDB.RequestError: Server user not authenticated.
at Operation.parseError (/home/mklaus/IdeaProjects/Thesis/node_modules/orientjs/lib/transport/binary/protocol28/operation.js:855:13)
at Operation.consume (/home/mklaus/IdeaProjects/Thesis/node_modules/orientjs/lib/transport/binary/protocol28/operation.js:446:35)
at Connection.process (/home/mklaus/IdeaProjects/Thesis/node_modules/orientjs/lib/transport/binary/connection.js:383:17)
at Connection.handleSocketData (/home/mklaus/IdeaProjects/Thesis/node_modules/orientjs/lib/transport/binary/connection.js:284:17)
at emitOne (events.js:90:13)
at Socket.emit (events.js:182:7)
at readableAddChunk (_stream_readable.js:147:16)
at Socket.Readable.push (_stream_readable.js:111:10)
at TCP.onread (net.js:525:20)
To find the Issue I logged my Server at this Moment and get:
Server {
useToken: false,
logger:
{ error: [Function: bound bound ],
log: [Function: bound bound ],
debug: [Function] },
transport:
BinaryTransport {
domain: null,
_events: { reset: [Function: bound ] },
_eventsCount: 1,
_maxListeners: Infinity,
connecting:
Promise {
_bitField: 268566529,
_fulfillmentHandler0: undefined,
_rejectionHandler0: undefined,
_progressHandler0: undefined,
_promise0: undefined,
_receiver0: undefined,
_settledValue: [Circular],
_boundTo: [Circular] },
closing: false,
retries: 0,
maxRetries: 5,
host: 'localhost',
port: 2424,
username: 'admin',
password: 'admin',
servers: [ [Object] ],
currentServer: 0,
enableRIDBags: true,
useToken: false,
token: <Buffer >,
sessionId: 62,
logger:
{ error: [Function: bound bound ],
log: [Function: bound bound ],
debug: [Function] },
connection:
Connection {
domain: null,
_events: [Object],
_eventsCount: 3,
_maxListeners: Infinity,
host: 'localhost',
port: 2424,
socket: [Object],
logger: [Object],
enableRIDBags: true,
closing: false,
reconnectNow: false,
protocol: [Object],
queue: [],
writes: [],
remaining: null,
connecting: false,
protocolVersion: 32 },
skipServerConnect: true },
config:
{ get: [Function: bound ],
set: [Function: bound ],
list: [Function: bound ] },
domain: null,
_events:
{ reset:
[ [Function: bound ],
[Function: bound ],
[Function: bound ],
[Function: bound ],
[Function: bound ] ],
error: [ [Object], [Object] ] },
_eventsCount: 2,
_maxListeners: Infinity }
As you can see the username and the Password is wrong. Someone know why this happen? Why I cant have Access to the Server after working with one DB on it?
*edit
Here is the Code of my nodejs Server (Not everything, just the important parts)
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var stringify = require('json-stringify-safe');
var routes = require('./routes/index');
var users = require('./routes/users');
var passport = require('passport');
var expressSession = require('express-session');
var Strategy = require('passport-local').Strategy;
var users = {};
var databases = {};
var OrientDB = require('orientjs');
var orientserver = OrientDB({
host: 'localhost',
port: 2424,
httpPort: 2480,
username: 'root',
password: 'Orientdb'
});
passport.use(new Strategy({
usernameField: 'username',
passwordField: 'password',
passReqToCallback: true
},
function(req, username, password, cb) {
var sessID = req.sessionID;
var dbkey = username+"_"+req.params.database;
if(dbkey in databases) {
} else {
databases[dbkey] = orientserver.use({
name: req.params.database,
username: username,
password: password
});
}
users[sessID]= {id: sessID, username: username, database: dbkey};
return cb(null, users[sessID]);
}));
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(expressSession({secret: 'mySecretKey', cookie: { maxAge: 60000 }}));
app.use(passport.initialize());
app.use(passport.session());
app.get('/', function (req, res) {
});
app.get('/getAllProjects', function(req, res) {
//https://github.com/kriskowal/q
orientserver.list()
.then(function (dbs) {
var json = [];
dbs.forEach(function(value, index) {
json.push({"name": value.name});
});
//console.log('There are ' + dbs.length + ' databases on the server.');
res.status(200).send(json);
});
});
app.post('/:database',
passport.authenticate('local', { failureRedirect: '/' }),
function(req, res) {
res.redirect("/"+req.params.database);
});
So when I send the second Request to getAllProjects I get the Error.