I have taken free trail from 2 factor for sending sms as otp and needs to be verified again, I am able to send the sms and also console.log the status on node side, but the issue is I am not able to send the response to client weather otp is sent or not and how could I verify it
What I have done till now
let otp = Math.floor(100000 + Math.random() * 900000) // geterating otp
const no = req.body.cPhoneNo //phone no from UI
console.log(no)
var options = {
"method": "POST",
"hostname": "2factor.in",
"port": null,
"path": "/API/V1/{{api_key}}/ADDON_SERVICES/SEND/TSMS",
"headers": {}
};
var req = http.request(options, function(res) {
var chunks = [];
res.on("data", function(chunk) {
chunks.push(chunk);
});
res.on("end", function() {
var body = Buffer.concat(chunks);
let sendData = body.toString()
console.log(body.toString())
res.json({status:body.toString}) //here I am getting error as type error json is not a function
});
});
req.write(JSON.stringify({
From: 'something',
To: no,
TemplateName: 'some Name',
VAR1: 'var 1',
VAR2: otp
// SendAt: '{OptionScheduleTime}'
}));
req.end();
I have mentioned with comment Where I am trying to send status back to client if it is send or not, but it is not taking json as throwing error .json throws type error
**One more thing I found from there website is **
I have found two url end points one to send sms with some session Id and other to get otp entered from user and verify that These are two urls
To send Otp https://2factor.in/API/V1/{api_key}/SMS/{phone_number}/AUTOGEN
To receive Otp https://2factor.in/API/V1/{api_key}/SMS/VERIFY/{session_id}/{otp_input}
api_key= The key I have got from 2factor
phone_number = receivers no
My issue is How I can use this endpoints to send the sms and to do verification, from client end I am on button click I am sending req to server via axios but in backend I have been suffering to send the msg and verify the otp
You can check out this link
Anyone out here please guide me
I don't see res.json method in node's HTTP module. Express has res.json method. Instead you should use JSON.parse. Have a look at this example from documentation.
Related
I call a POST method with javascript using fetch, Checked my server logs and see these lines:
2020-02-08,14:07:21 [WARNING] (web.py:web:1618): 400 POST /login (::1): Missing argument username
2020-02-08,14:07:21 [WARNING] (web.py:web:2106): 400 POST /login (::1) 8.64ms
...
2020-02-08,14:07:21 [DEBUG] (base_handler.py:base_handler:123): Attempted Sign-in by asdas
2020-02-08,14:07:21 [INFO] (web.py:web:2106): 200 POST /login (::1) 6.07ms
Here is the js which sends the request and then uses the response to add text to the page if login is unsuccessful:
function ready(){
function pwdSubmission(){
const url = window.location.href;
var result = document.getElementById("result-text");
var username = document.getElementById("user").value;
var password = document.getElementById("pwd").value;
fetch(url, {method:"post", headers:{
"Content-Type": "application/json",
"Accept": "application/json"},
body:{"username":username, "password":password}}
).then(function(data){
if (data.status !== 200){
result.style.color = '#d9534f';
}
return data.json()
}).then(data =>
result.innerText = data["message"])
}
var postbtn = document.getElementById("post-btn");
postbtn.addEventListener("click", pwdSubmission)
}
So why is the POST sent twice and the first time it doesn't include the arguments.
UPDATE
My server have no problem grabbing the arguments from the body even without stringify but there is no body in the first request, only the second, so I get an error which sends json back
The body param isn't correct. You're passing an object when it should be a JSON string.
body:JSON.stringify({username:username, password:password}})
Figured it out. My inputs were wrapped in a form tag and the button was defaulting to a form submit so I removed those tags and it only sends once now.
Your body data type must match your "Content-Type" header ("application/json" in your case).
Using ES6 object shorthand you could do...
body: JSON.stringify({username, password})
I am stuck on something in sockets.io I want to send something to the server.js and then resend some of the data back out to everyone else connected.
So I would like to send something like
I have
userid="1"
username="dave"
message="some message"
So I would send it like :
userid:userid,
username:username,
message:message
At the moment I am only sending one paramater, 'message' like so :-
function sendmessage() {
var new_message = document.getElementById("message").value;
socket.emit('new_message', new_message);
}
and for the sever :
socket.on('new_message', function (data) {
console.log(data);
});
So I get the message ok but how do I send and receive and read the the rest and then send some of the data back out to everyone. Sorry but this is doing my head in and all the tutorials are just for sending msg.
To send a message to every socket connected : doc
io.emit('some event', { for: 'everyone' });
To answer your question about how to send multiple parameter, one way of doing this is to send an object with multiple keys.
function sendmessage() {
socket.emit('new_message', { userid, username, message });
}
socket.on('new_message', function(data){
console.log(`${data.userid} - ${data.username} - ${data.message} `);
});
I'm developing a SAPUI5 app and use the FileUploader control in my app to upload documents to a server. The uploading works and I also receive a response from the server (I can see this in the DevTools of Chrome).The problem is that the event-object inside the 'uploadComplete' event-handler always returns undefined for the response parameter.
Do you know why this is the case and how I can fix it?
Here is the initialization of the FileUploader:
var oFileUploader = new sap.ui.unified.FileUploader({
uploadUrl: "/fileupload",
name: "documentUploader",
uploadOnChange: false,
multiple: false,
width: "400px",
uploadComplete: this.onDocumentUploadComplete
});
And here is the 'uploadComplete' event-handler:
onDocumentUploadComplete: function(oEvent) {
var response = oEvent.getParameter("response");
console.log(response); // response = undefined
}
I still haven't figured out how to receive the server's response but I have found a workaround.After uploading the file I just send a request to the server and tell it to check whether the file exists.If it exists the server returns "true" and if it doesn't the server returns "false". Here's my code:
// eventhandler for the "uploadComplete"-event of the FileUploader-control
onDocumentUploadComplete: function(oEvent) {
var uploaderControl = oEvent.getSource();
var documentname = uploaderControl.getValue();
var fileURI = "/file/" + documentname + "?exists";
$.get(fileURI, function(data) {
if (data === "true") {
console.log("Successfully uploaded: " + documentname);
this.handleDocumentUploadSuccess(documentname);
} else {
console.log("Error when uploading document: " + documentname);
this.handleDocumentUploadError(documentname);
}
}.bind(this));
}
According to the documentation the parameter response is subject to some conditions.
Response message which comes from the server. On the server side this
response has to be put within the "body" tags of the response document
of the iFrame. It can consist of a return code and an optional
message. This does not work in cross-domain scenarios.
That means the response fom the server must be XML or HTML.
How can i post a custom JSON Message with formatting & indented using slack webhook? I am using nodejs app
var Slack = require('slack-node');
var JsonMessage = process.argv[2];
webhookUri = "https://hooks.slack.com/services/XXXX/xxxx/xxxxxxxx";
slack = new Slack();
slack.setWebhook(webhookUri);
var textmsg = '```' + JsonMessage + '```';
slack.webhook({
channel: "#status",
username: "Monitor Bot",
icon_emoji: ":ghost:",
text: textmsg
}, function(err, response) {
console.log(response);
});
The above code helps to send the JSON but it is not in formatted one. It comes as a string. I would like to have the JSON indented.
Thank you.
Your JsonMessage argument is just a string, therefore it is sent as such to slack. I'd suggest sending it through JSON.parse to convert it into native JavaScript objects. You can then send it through a formatter to format it properly for you. e.g.
var formatter = ('format-json');
var formattedJson = formatter.plain(JSON.parse(JsonMessage));
I really suck at understanding scopes and other things of that nature in just about every language. Right now I am building an express application that takes user input and then queries an arbitrary api and then feeds it to the console. To handle the rest api, I am using shred. I know I can use nodes built in get request, but for some reason, I could never get it to work. The user makes the following get request to my app, /query?query=. This is what I have now. I can't really describe what I'm doing so pleas read the code comments.
var http = require('http');
var Shred = require("shred");
var assert = require("assert");
exports.query = function(req, res){
//thequery is the string that is requested
var thequery = req.query.query;
var shred = new Shred();
console.log("user searched" + " " + thequery);
console.log();
//The if statement detects if the user searched a url or something else
if (thequery.indexOf("somearbitratyrestapi.com") !== -1){
console.log("a url was searched");
//find info on the url
var thedata = shred.get({
url: "http://somearbitratyrestapi.com/bla/v2" + thequery,
headers: {
Accept: "application/json"
},
on: {
// You can use response codes as events
200: function(response) {
// Shred will automatically JSON-decode response bodies that have a
// JSON Content-Type
//This is the returned json
//I want to get this json Data outside the scope of this object
console(response.content.body);
},
// Any other response means something's wrong
response: function(response) {
console.log("ohknowz");
}
}
});
//I want to be able to see that json over here. How do?
}else{
console.log("another thing was searched");
}
/*
res.render('search-results', {
result: 'you gave me a url',
title: 'you gave me a url'
});
*/
};
I tried doing this
var http = require('http');
var Shred = require("shred");
var assert = require("assert");
exports.query = function(req, res){
//thequery is the string that is requested
var thequery = req.query.query;
var shred = new Shred();
//I created a variable outside of the object
var myjson;
console.log("user searched" + " " + thequery);
console.log();
//The if statement detects if the user searched a url or something else
if (thequery.indexOf("somearbitratyrestapi.com") !== -1){
console.log("a url was searched");
//find info on the url
var thedata = shred.get({
url: "http://somearbitratyrestapi.com/bla/v2" + thequery,
headers: {
Accept: "application/json"
},
on: {
// You can use response codes as events
200: function(response) {
// Shred will automatically JSON-decode response bodies that have a
// JSON Content-Type
//This is the returned json
//I set myjson to the returned json
myjson = response.content.body
},
// Any other response means something's wrong
response: function(response) {
console.log("ohknowz");
}
}
});
//Then I try to output the json and get nothing
console.log(myjson);
}else{
console.log("another thing was searched");
}
/*
res.render('search-results', {
result: 'you gave me a url',
title: 'you gave me a url'
});
*/
};
Sorry for the bad explanation of my problem. Can someone please help or explain what is going on.
So you think you need to move data out of your nested scope, but the opposite is true. Within the nested scope where you have access to your upstream JSON response, you need to access the res object and send it though:
myjson = response.content.body
res.send(myjson);
However, long term you'll need to do some more node tutorials and focus on how to use callbacks to avoid deeply nested function scopes.