Data Changes between Axios Post Implementation - axios

pages/login
const data = ({
email: email,
password: password
})
console.log(data)
const {details} = await axios.post('/api/users/login', data, {
headers: {
"Content-Type": "application/json",
}
})
pages/api/login
const handler = nc();
console.log('beginning login api')
handler.post(async(req, res) => {
await database.connect();
console.log('db connected')
console.log(req)
My issue is that the console.log data in the login is logging out correctly but the req being printed out in the api is logging a long list which I will provide a snippet of
<ref *2> IncomingMessage {
_readableState: ReadableState {
objectMode: false,
highWaterMark: 16384,
buffer: BufferList { head: null, tail: null, length: 0 },
length: 0,
pipes: [],
flowing: true,
ended: true,
endEmitted: true,
reading: false,
constructed: true,
sync: true,
needReadable: false,
emittedReadable: false,
readableListening: false,
resumeScheduled: false,
errorEmitted: false,
console.log(data) output
UPDATE----
const user = await user.findOne({ email: req.body.email});
res.send ({
token,
email: user.email,
name: user.name,
_id: user._id,
createdAt: user.createdAt
})
this returns the server response list I refer to. I tried req.body. for each instead of the user. as well but got the same response.
UPDATE 2
So the axios request and response on the API side are both correct.
when I console.log(details) which is assigned to the axios request it returns undefined.

That "long list" you're seeing from pages/api/login is the IncomingMessage object. If you're looking for just the data, you want to console.log(req.body).

for the axios.post const, it has to be named data not details or any other name, there is a strict 5/6 names that can be destructue

Related

axios is showing data in console but not posting in mongo db

Hi I am using axios to post my string and some buffer data in my mongodb server.Data is working fine with post but when I try to post data using axios it does show on console but it doesnot post data in mongo db here is my axios post code
axios.js
const formData = new FormData();
formData.append("name", this.state.name);
formData.append("title", this.state.title);
formData.append("contact", this.state.contact);
formData.append("price", this.state.price);
formData.append("description", this.state.description);
formData.append("selectedcat", this.state.selectedcat);
formData.append("selectedcity", this.state.selectedcity);
formData.append("imgforsell", this.state.imgforsell);
axios
.post(
// `http://${
// Platform.OS === "android" ? "192.168.88.45" : "localhost"
//}:4000/pets/addpets`,
'http://http://192.168.88.45:4000/pets/addpets',
formData,
{headers: { "Content-Type": "multipart/form-data" }}
)
.then(({ data }) => {
console.log(data);
})
.catch((err) => {
console.error(err.toJSON());
// res.status(500).json(err) 👈 don't do this, it's not Express
})
.finally(() => {
this.setState({
name: "",
title: "",
contact: "",
price: "",
description: "",
selectedcat: "",
selectedcity: "",
imgforsell: "",
});
});
and here is the console data
Object {
"code": undefined,
"columnNumber": undefined,
"config": Object {
"adapter": [Function xhrAdapter],
"data": "{"_parts":[["name","Saad"],["title","Pets"],["contact","12345678900"],["price","123"],["description","Post"],["selectedcat","Pets Accessories"],["selectedcity","Karachi"],["imgforsell",{"cancelled":false,"width":2160,"exif":{"DateTime":"2015:11:04 17:32:48","Software":"Adobe Photoshop CC (Windows)","XResolution":72,"ImageWidth":2160,"Orientation":0,"ImageLength":1620,"ResolutionUnit":2,"LightSource":0,"ColorSpace":1,"JPEGInterchangeFormat":302,"YResolution":72,"Compression":6,"JPEGInterchangeFormatLength":5674},"height":1620,"base64":"/9j/4QG+RXhpZgAATU0AKgAAAAgADAESAAQAAAABAAAAAAEAAAQAAAABAAAIcAEaAAUAAAABAAAAngExAAIAAAAdAAAApgICF/nat node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:388:6 in __callImmediatesat node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:132:6 in __guard$argument_0at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:365:10 in __guardat node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:131:4 in flushedQueue
update.js
const petsObject = {
name: this.state.name,
title: this.state.title,
contact: this.state.contact,
price: this.state.price,
description: this.state.description,
selectedcat:this.state.selectedcat,
imgforsell:this.state.imgforsell
};
axios
.post(
// `http://${
// Platform.OS === "android" ? "192.168.88.45" : "localhost"
// }:4000/pets/addpets`,
//'http://192.168.88.45:4000/pets/addpets/',
'http://localhost:4000/Pets/addpets/',
// formData,
petsObject,
{
headers: {
'Content-Type': 'application/json',
},
transformRequest: (formData,headers) => {
return formData; // this is doing the trick
},
},
)
.then(({ data }) => {
console.log(data);
// .then(res => {
// console.log('Data Posted',res);
// }
}
)
.catch((err) => {
console.error(err.toJSON());
// res.status(500).json(err) 👈 don't do this, it's not Express
})
.finally(() => {
this.setState({
name: "",
title: "",
contact: "",
price: "",
description: "",
selectedcat: "",
selectedcity: "",
imgforsell: "",
});
});
Have you ever checked your backend. Maybe you didn't commit the changes. You need to debug in your backend.

Accessing Flutter callkit Incoming Calls Params

am at the moment making use of this particular flutter package for my project but I can't access the params, please I really need your help
flutter_callkit_incoming: ^1.0.0+8
when am to receive an incoming call I use the below code
this._currentUuid = _uuid.v4();
var params = <String, dynamic>{
'id': _currentUuid,
'nameCaller': data.fromFullName,
'appName': 'Prayer Buddy',
'avatar': data.fromImage,
'handle': 'Prayer Partner Calling',
'type': type,
'duration': 30000,
'extra': <String, dynamic>{'userId': '1a2b3c4d'},
'headers': <String, dynamic>{'apiKey': 'Abc#123!', 'platform': 'flutter'},
'android': <String, dynamic>{
'isCustomNotification': true,
'isShowLogo': false,
'ringtonePath': 'ringtone_default',
'backgroundColor': '#0955fa',
'backgroundUrl': data.toImage,
'actionColor': '#4CAF50'
},
'ios': <String, dynamic>{
'iconName': 'AppIcon40x40',
'handleType': 'generic',
'supportsVideo': true,
'maximumCallGroups': 2,
'maximumCallsPerCallGroup': 1,
'audioSessionMode': 'default',
'audioSessionActive': true,
'audioSessionPreferredSampleRate': 44100.0,
'audioSessionPreferredIOBufferDuration': 0.005,
'supportsDTMF': true,
'supportsHolding': true,
'supportsGrouping': false,
'supportsUngrouping': false,
'ringtonePath': 'Ringtone.caf'
}
};
await FlutterCallkitIncoming.showCallkitIncoming(params);
on the FlutterCallkitIncoming.onEvent.listen((event) function am trying to access the params sent via the showCallkitIncoming(params)
so i did a print of the event print(event) the output was below
{ event: com.hiennv.flutter_callkit_incoming.ACTION_CALL_ENDED, body: {duration: 30000, extra: {userId: 1a2b3c4d}, uuid: 1fa5d670-5698-40fa-8705-bd794304fa96, avatar: http://arome.joons-me.com/user_img/james/images/image_picker_F27FD117-E882-4C51-9143-943E3BF4A8CF-24547-00000899F347179A.jpg, type: 0, nameCaller: James Amadin, handle: Prayer Partner Calling, appName: Prayer Buddy, ios: {supportsHolding: true, audioSessionPreferredIOBufferDuration: 0.005, supportsDTMF: true, maximumCallGroups: 2, includesCallsInRecents: true, audioSessionPreferredSampleRate: 44100.0, iconName: AppIcon40x40, supportsVideo: true, supportsGrouping: false, audioSessionActive: true, audioSessionMode: default, maximumCallsPerCallGroup: 1, supportsUngrouping: false, handleType: generic, ringtonePath: Ringtone.caf}} }
I want to access the extra from the return JSON, please how do I do that?
but when i tried to access it via the below code
try {
dynamic myMap = json.decode(event!.body);
if (myMap is! Map<String, dynamic>) throw FormatException();
final message = myMap['extra'];
print('1message == ${message}');
} catch (error) {
print('JSON is in the wrong format');
}
I got JSON is in the wrong format
I was able to resolve it by the following code
print(event!.body['extra']['userId']);
print(event.body['extra']['to_user']);
print(event.body['extra']['from_user']);

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");
});
});

Can make post request to localhost using node-fetch, but unable to do so using 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: ''
}

make request in axios with credentials and data

I need to make this request but in axios
$.ajax({
type: "POST",
url: url,
data: {'HTTP_CONTENT_LANGUAGE': 'en'},
xhrFields: {
withCredentials: true
},
I tried
params = {
data: {
'HTTP_CONTENT_LANGUAGE': 'en',
},
withCredentials: true
};
axios.post(url, params)
But didn't work what do I do?