How to send a request to an api in express js inside a route
I have a post route that carries the phone number of a user. I receive it and want to send an request to an api to send an otp/sms,
app.post('/sendotp', function(req, res){
//i want to send a api request to
http://2factor.in/API/V1/{APIKEY}/SMS/'+no+'/AUTOGEN
// i would like to have a response here
//eg: { "Status": "Success", "Details": "ff9ab5b0-452e-11e7-94da-0200cd936042"}
}
Let me know how to handle this
Attempts:
app.get('/apiotp', function(req, res){
var url = 'http://2factor.in/API/V1/0d9cb422-3042/SMS/'+no+'/AUTOGEN';
fetch(url)
.then(function(resp){
console.log(resp);
res.send('done');
})
.catch(function(err){
console.log(error);
});
})
A2:
app.get('/apiotp', function(req, res){
http.request(options, function (res){
console.log(res);
// res.send('done');
})
})
See also questions close to this topic
-
Custom Vue library component with <router-link>, how to synchronize router state?
I am attempting to create a re-usable navigation component, that uses vue-router
<router-link>
to navigate. The specific navigation elements also change styles based on active links.If I import this component "raw", as in the .vue file, this works fine and the router state is synchronized and the links work.
However if I build my components and export them as a library (using webpack), my routes stop working. All the other features of the component work, scripts, events, properties, styles and such.
Would this be a problem with my webpack build config, or do I need to pass in some type of property that can link together the state of my application to my component?
-
Spreadjs sheet converts Values like 1E, 2E to 1.00E+00, 2.00E+00
I have implemented spreadjs (v11) workbook in my project. Whenever i am entering values like 1E, 2E .... in cell it automatically gets converted to 1.00E+00, 2.00E+00 etc. Same when i am selecting values like 1E,2E... from list(from list validator dropdown) , spredjs converts them to above mention format. Please suggest me any solution. Thanks in Advance.
-
I'd like to get a group of clients online when I click the on-air or off-air button. I also want to show all; both on-air and off-air
I need help with this code. Like described in the above title, I want to click on a button to see the list of twitch clients both on-air on one part and off-air in another part or even show all twitch client currently broadcasting or not. My HTML and javascript code is below:
$(document).ready(function() { users = ["ESL_SC2", "OgamingSC2", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas", "ZoomPC", "Xbox", "Wolsk", "silgarth"]; for (let i = 0; i < users.length; i++) { let baseUrl = "https://wind-bow.glitch.me/twitch-api/channels/"; let tailUrl = users[i]; let webLink = baseUrl + tailUrl; let stream = "https://wind-bow.glitch.me/twitch-api/streams/"; let streamLink = stream + tailUrl; let pre = document.getElementsByClassName("out")[0]; $.ajax({ url: webLink, type: "GET", dataType: "json", success: function(data) { console.log(data); $.ajax({ url: streamLink, type: "GET", dataType: "json", success: function(result) { console.log(result._links); if(result.stream === null){ pre.innerHTML += "<div class='row listing'><div class='col-sm-3 logo'><img class = 'img-responsive' src=" + data.logo + "></div><div class='row text'><div class='col-sm-12 name'><p><a href="+ data.url +" target = '_blank'>" + data.display_name + "</a></p></div><div class='row status'><div class='col-sm-12 worx'><p class='neon' style='color:black;'> OFF-AIR </p></div></div></div>" }else{ pre.innerHTML += "<div class='row listing'><div class='col-sm-3 logo'><img class = 'img-responsive' src=" + data.logo + "></div><div class='row text'><div class='col-sm-12 name'><p><a href="+ data.url +" target = '_blank'>" + data.display_name + "</a></p></div><div class='row status'><div class='col-sm-12 worx'><p class='neon' style='color:#32CD32;'> ON-AIR </p></div></div></div>" } }, error: function() { alert("Something went wrong with the server..."); } }); }, error: function() { alert("Something went wrong with the server...."); } }); } });
.container-fluid{ background-color: #1565C0; min-height: 630px; background-image: url('data:image/svg+xml,%3Csvg width="100" height="20" viewBox="0 0 100 20" xmlns="http://www.w3.org/2000/svg"%3E%3Cpath d="M21.184 20c.357-.13.72-.264 1.088-.402l1.768-.661C33.64 15.347 39.647 14 50 14c10.271 0 15.362 1.222 24.629 4.928.955.383 1.869.74 2.75 1.072h6.225c-2.51-.73-5.139-1.691-8.233-2.928C65.888 13.278 60.562 12 50 12c-10.626 0-16.855 1.397-26.66 5.063l-1.767.662c-2.475.923-4.66 1.674-6.724 2.275h6.335zm0-20C13.258 2.892 8.077 4 0 4V2c5.744 0 9.951-.574 14.85-2h6.334zM77.38 0C85.239 2.966 90.502 4 100 4V2c-6.842 0-11.386-.542-16.396-2h-6.225zM0 14c8.44 0 13.718-1.21 22.272-4.402l1.768-.661C33.64 5.347 39.647 4 50 4c10.271 0 15.362 1.222 24.629 4.928C84.112 12.722 89.438 14 100 14v-2c-10.271 0-15.362-1.222-24.629-4.928C65.888 3.278 60.562 2 50 2 39.374 2 33.145 3.397 23.34 7.063l-1.767.662C13.223 10.84 8.163 12 0 12v2z" fill="%239C92AC" fill-opacity="0.4" fill-rule="evenodd"/%3E%3C/svg%3E'); } .out{ /*border: 1px solid brown;*/ width: 500px; margin-top: 110px; margin-bottom: 30px; height: auto; background-color: rgba(0, 0, 0, 0.5); } .rw{ margin-top: -15px; width:470px; margin-left: -1px; margin-bottom: 5px; } .rs{ height: 30px; margin-top: 5px; width:470px; margin-left: -1px; } .jmb{ margin-top: 20px; } .line{ margin-top: -25px; } .listing{ border: 1px solid grey; width: 470px; height: 110px; margin-left: -1px; margin-top: 10px; margin-bottom: 4px; } .logo{ /*border: 1px solid whitesmoke;*/ height: 104px; margin-left: 4px; margin-top: 2px; background-color: whitesmoke; } .logo img{ padding-top:8px; } .text{ /*border: 1px solid whitesmoke;*/ height: 48px; width: 340px; margin-left: 123px; margin-top: 2px; background-color: black; } .status{ border: 1px solid whitesmoke; height: 54px; width: 340px; margin-left: -1px; margin-top: 48px; } .neon{ font-weight: bold; padding-top:22px; } .name>p{ padding-top:20px; font-size:16px; }
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="container-fluid"> <div class="container out"> <div class="jumbotron jmb"> <img class="img-responsive" src="./assets/image/twitch.png" alt=""> </div> <div class="page-header line"></div> <div class="row rw"> <div class="btn-group btn-group-justified"> <a href="#" class="btn btn-primary all">ALL</a> <a href="#" class="btn btn-primary on">ON-AIR</a> <a href="#" class="btn btn-primary off">OFF-AIR</a> </div> </div> </div> </div>
-
Facebook messenger: initiate conversation from bot to user on bot framework using node.js
I am trying to create a chatbot whereby when user revisit the chat on facebook messenger, it will detect and initiate conversation.
Could someone please advise me?
My current code:
bot.on('conversationUpdate', function (message) { if (message.membersAdded) { message.membersAdded.forEach(function (identity) { if (identity.id === message.address.bot.id) { bot.beginDialog(message.address, 'revisitDialog'); } }); } });
Expected result:
Bot to User: Ans A User to bot: What is b? Bot to User: Ans B After an hour, when the user revisit the chat.... Bot to user: hi, is there anything I can help you with?
-
lerna fatal: ambiguous argument 'origin/heads/origin/master...heads/origin/master': unknown revision or path not in the working tree
This is apart of my series of questions pertaining to how to get lerna running in Jenkins.
Previous issues:
lerna publish on Jenkins "git remote update" Fails "Could not read from remote repository."
> lerna publish --yes --cd-version=patch lerna info version 3.0.0-beta.17 lerna info versioning independent lerna ERR! Error: Command failed: git rev-list --left-right --count origin/heads/origin/master...heads/origin/master lerna ERR! fatal: ambiguous argument 'origin/heads/origin/master...heads/origin/master': unknown revision or path not in the working tree. lerna ERR! Use '--' to separate paths from revisions, like this: lerna ERR! 'git <command> [<revision>...] -- [<file>...]' lerna ERR! lerna ERR! lerna ERR! at makeError (/var/lib/jenkins/workspace/abide/node_modules/@lerna/child-process/node_modules/execa/index.js:169:9) lerna ERR! at Function.module.exports.sync (/var/lib/jenkins/workspace/abide/node_modules/@lerna/child-process/node_modules/execa/index.js:338:15) lerna ERR! at Object.execSync (/var/lib/jenkins/workspace/abide/node_modules/@lerna/child-process/index.js:21:16) lerna ERR! at Object.isBehindUpstream (/var/lib/jenkins/workspace/abide/node_modules/@lerna/git-utils/index.js:209:48) lerna ERR! at PublishCommand.initialize (/var/lib/jenkins/workspace/abide/node_modules/@lerna/publish/index.js:92:24) lerna ERR! at Promise.resolve.then (/var/lib/jenkins/workspace/abide/node_modules/@lerna/command/index.js:228:24) lerna ERR! lerna Command failed: git rev-list --left-right --count origin/heads/origin/master...heads/origin/master lerna ERR! lerna fatal: ambiguous argument 'origin/heads/origin/master...heads/origin/master': unknown revision or path not in the working tree. lerna ERR! lerna Use '--' to separate paths from revisions, like this: lerna ERR! lerna 'git <command> [<revision>...] -- [<file>...]' lerna ERR! lerna lerna ERR! lerna npm ERR! code ELIFECYCLE npm ERR! errno 128 npm ERR! abide@1.0.0 publish: `lerna publish --yes --cd-version=patch` npm ERR! Exit status 128 npm ERR! npm ERR! Failed at the abide@1.0.0 publish script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. npm ERR! A complete log of this run can be found in: npm ERR! /var/lib/jenkins/.npm/_logs/2018-04-24T05_32_38_890Z-debug.log npm ERR! code ELIFECYCLE npm ERR! errno 128 npm ERR! abide@1.0.0 jenkins: `npm run versions && npm run test && npm run publish` npm ERR! Exit status 128 npm ERR! npm ERR! Failed at the abide@1.0.0 jenkins script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. npm ERR! A complete log of this run can be found in: npm ERR! /var/lib/jenkins/.npm/_logs/2018-04-24T05_32_38_901Z-debug.log
-
aggregate by number of occurrences and count in mongo
I need to aggregate the following data and count the number of occurrences using mongod, I already have the logic in javascript but I need to do it with mongoose.
var data = [ {name:'tyler', age:25, email:'abc1@xyz.com'}, {name:'durden', age:26, email:'abc2@xyz.com'}, {name:'brad', age:26, email:'abc3@xyz.com'}, {name:'tyler', age:25, email:'abc4@xyz.com'}, {name:'brad', age:25, email:'abc5@xyz.com'}, {name:'tyler', age:27, email:'abc6@xyz.com'}, {name:'tyler', age:25, email:'abc1@xyz.com'}, {name:'durden', age:26, email:'abc2@xyz.com'},
]
js code
var uniqueNames = data.reduce(function(acc,cv){ var arr = acc.filter(function(obj){ return obj.name === cv.name && obj.age === cv.age; }) if(arr.length === 0){ acc.push({name:cv.name, age:cv.age, count:1}) }else{ arr[0].count += 1; } return acc;
}, [])
excepted out put using mongo
var output = [ { name: "tyler", age: 25, count: 3 }, { name: "durden", age: 26, count: 2 }, { name: "brad", age: 26, count: 1 }, { name: "brad", age: 25, count: 1 }, { name: "tyler", age: 27, count: 1 }
]
-
How is Laravel decoding HTTP request body Content-Type: application/x-www-form-urlencoded when using api call
I'm using Laravel-5.5 and i'm developing an apis for an iOS app.
Here, i'm using postman to call all apis. I've one registration api with two headers:
1)
Authorization: Bearer access_token
2)
Content-type: application/x-www-form-urlencoded
Now when i requesting this api i just want to print
dd($request->all());
But it's not give me proper request data. I've triedjson_decode(urldecode(file_get_contents('php://input')));
to decode it and also tried$request->getContent();
but no luck!Can anyone knows how to get request data in controller when using
Content-type: application/x-www-form-urlencoded
??EDIT:
public function registration(Request $request) { dd($request->all()); dd($request->getContent()); //also tried but not work dd(json_decode(urldecode(file_get_contents('php://input')))); //no luck }
-
Failed to get StepCount Using Google Fit API
Login to Google Fit account success but step count is not showing. Please help
public class MainActivity extends AppCompatActivity { public static final int GOOGLE_FIT_PERMISSIONS_REQUEST_CODE=101; public static final String TAG="StepCounter"; private static final int REQUEST_OAUTH = 1; private static final String AUTH_PENDING = "auth_state_pending"; private boolean authInProgress = false; private GoogleApiClient mClient = null; ProgressBar progressBar; public static Boolean loggedIn=false; @Override protected void onStart() { super.onStart(); // Connect to the Fitness API Log.i(TAG, "Connecting..."); mClient.connect(); } @Override protected void onStop() { super.onStop(); if (mClient.isConnected()) { mClient.disconnect(); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_OAUTH) { authInProgress = false; if (resultCode == RESULT_OK) { // Make sure the app is not already connected or attempting to connect if (!mClient.isConnecting() && !mClient.isConnected()) { mClient.connect(); } } } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); progressBar=(ProgressBar)findViewById(R.id.progressBar); if (savedInstanceState != null) { authInProgress = savedInstanceState.getBoolean(AUTH_PENDING); } buildFitnessClient(); new Thread(new Runnable() { //worker thread adding data to the array list(the data can be from database) @Override public void run() { while(loggedIn) { readData(); try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } } } }).start(); } private void buildFitnessClient() { mClient = new GoogleApiClient.Builder(this) .addApi(Fitness.SENSORS_API) .addScope(new Scope(Scopes.FITNESS_LOCATION_READ)) .addConnectionCallbacks( new GoogleApiClient.ConnectionCallbacks() { @Override public void onConnected(Bundle bundle) { Log.i(TAG, "Connected!!!"); progressBar.setVisibility(View.INVISIBLE); loggedIn=true; // Now you can make calls to the Fitness APIs. // Put application specific code here. } @Override public void onConnectionSuspended(int i) { // If your connection to the sensor gets lost at some point, // you'll be able to determine the reason and react to it here. if (i == GoogleApiClient.ConnectionCallbacks.CAUSE_NETWORK_LOST) { Log.i(TAG, "Connection lost. Cause: Network Lost."); } else if (i == GoogleApiClient.ConnectionCallbacks.CAUSE_SERVICE_DISCONNECTED) { Log.i(TAG, "Connection lost. Reason: Service Disconnected"); } } } ) .addOnConnectionFailedListener( new GoogleApiClient.OnConnectionFailedListener() { // Called whenever the API client fails to connect. @Override public void onConnectionFailed(ConnectionResult result) { Log.i(TAG, "Connection failed. Cause: " + result.toString()); if (!result.hasResolution()) { // Show the localized error dialog GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), MainActivity.this, 0).show(); return; } // The failure has a resolution. Resolve it. // Called typically when the app is not yet authorized, and an // authorization dialog is displayed to the user. if (!authInProgress) { try { Log.i(TAG, "Attempting to resolve failed connection"); authInProgress = true; result.startResolutionForResult(MainActivity.this, REQUEST_OAUTH); } catch (IntentSender.SendIntentException e) { Log.e(TAG, "Exception while starting resolution activity", e); } } } } ) .build(); }
The function for reading the stepcount from googlefit account
private void readData() { Fitness.getHistoryClient(this, GoogleSignIn.getLastSignedInAccount(this)) .readDailyTotal(DataType.TYPE_STEP_COUNT_DELTA) .addOnSuccessListener( new OnSuccessListener<DataSet>() { @Override public void onSuccess(DataSet dataSet) { long total = dataSet.isEmpty() ? 0 : dataSet.getDataPoints().get(0).getValue(Field.FIELD_STEPS).asInt(); Log.i(TAG, "Total steps: " + total); Toast.makeText(getApplicationContext(),String.valueOf(total),Toast.LENGTH_SHORT).show(); } }) .addOnFailureListener( new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Log.w(TAG, "There was a problem getting the step count.", e); Toast.makeText(getApplicationContext(),"error",Toast.LENGTH_SHORT).show(); } }); } }
When successfully login then readData() is called but no Log msg or Toast message is getting.
On debugging the
readData()
code is executing but no result is showing. -
Custom routing on Laravel
I have some problem with
routing in Laravel
. I have a route like this$app->get('manufaktur/{secretkey}','Rest\LkppController@get_manufaktur');
it will generate URL like this : https://baseurl/api/manufacture/my-secret-key.
Now, my problem is how to change that route so it would be like this https://baseurl/api/manufacture?secretkey=my-secret-key.
Thanks before.
-
Express : TypeError: user.company.pull is not a function
I'd like to remove an object element from my user object, I'm using pull to remove it, but it returns
TypeError: user.company.pull is not a function
router.put('/reset', passport.authenticate('jwt', {session:false}), (req, res, next)=> { user = req.user; var id_student = user.id; var id_company = user.company; var results = []; User.findById(id_student, function(err, user) { if(err) { console.log(err); return res.status(500).send({message: "Error"}); } if(!user) { return res.status(404).send({message: "User Not Found"}); } user.company.pull({'company': id_company}); res.send(user); }); });
-
(React and axios) Mern Data flow problems! Halp! :(
I am an aspiring react developer and I am having some issues with my app.
I am trying to scrape the new york times for an assignment I have, and I can get my data with a search to log serverside, but I cant seem to pass it back. I can get my data by pushing it to a mongo db then querying it in a separate process from the front end, but I don't want to do that. I want to pass the object back up the stack to the client side. Does anyone know how I might accomplish that?
here is some of my code.
my dir structure: image
here is the client folder structure: image
here is my Home.jsx file clientside in /pages:
import React, { Component } from 'react'; import { Container, Row, Column } from '../../components/BootstrapGrid'; import API from '../../utils/API' import {Input, FormBtn} from '../../components/Form' class Home extends Component { state = { formInput: "", posts: [], } loadArticles = (res) => { console.log('res') } handleInputChange = event => { const { name, value } = event.target; this.setState({ [name]: value }); }; handleFormSubmit = event => { event.preventDefault(); let query = this.state.formInput // console.log(query) API.scrapeArticles(query) // console.log(this.state) }; render() { return ( <Container> <Row> <Column> </Column> <Column> <Input value={this.state.formInput} onChange={this.handleInputChange} name="formInput" placeholder="Search Query (required)" /> <FormBtn onClick={this.handleFormSubmit}>Scrape NYT API</FormBtn> </Column> </Row> </Container> ); } } export default Home;
here is my code calling the clientside api in client/utils/api/:
import axios from "axios"; export default { // getPosts: function () { // return axios.get('/api/posts') // }, // savePost: function (postData) { // return axios.post("/api/posts", postData); // }, scrapeArticles: function (query) { // console.log(query) let queryData = { query: query } return axios.post('/api/scraper', queryData) } };
here is my code from the backend routes/index.js being hit by axios (i think? Im honestly not sure how but i think this is the flow):
const path = require("path"); const router = require("express").Router(); const postsController = require('../controllers/postsController') router.route("/") .get(postsController.getAll) .post(postsController.create); router.route('/api/scraper') .post(postsController.scraper) .get(postsController.scraper) // If no API routes are hit, send the React app router.use(function (req, res) { res.sendFile(path.join(__dirname, "../client/build/index.html")); }); module.exports = router;
here is my controller that is referenced in the file above:
const scraper = require('../scraper') const db = require('../models'); module.exports = { create: function (req, res) { db.Post .create(req.body) .then(dbmodel => res.json(dbmodel)) .catch(err => res.status(422).json(err)) }, getAll: function (req, res) { db.Post .find(req.query) .sort({date: -1}) .then(dbModel => res.json(dbModel)) .catch(err => res.status(422).json(err)) }, scraper: function (req, res) { let queryData = req.body.query scraper(queryData) }, scraperGet: function (req, res) { scraper() console.log(res.body) } }
and lastly, here is the scraper file on the backend:
const request = require('request'); const mongoose = require('mongoose'); const db = require('./models'); const scraper = (queryData) => { console.log(`@scraper ${queryData}`) let articleData = [] request.get({ url: "https://api.nytimes.com/svc/search/v2/articlesearch.json", qs: { 'api-key': "-----------------------------", "q" : queryData }, }, function (err, response, body) { body = JSON.parse(body); let articles = body.response.docs articles.forEach(element => { // console.log(element) let title= element.headline.main let url = element.web_url let synopsis = element.abstract let snippet = element.snippet let source = element.source let pubDate = element.pub_date let article = { title: title, url: url, synopsis: synopsis, snippet: snippet, source: source, pubDate: pubDate, } // console.log(article) articleData.push(article) db.Post.create({title:article.title}).then(article => { console.log(article) }).catch(err => { console.log(err) }) }); return articleData }); } module.exports = scraper;
So i know right now it is pushing to mongo. This is only because I couldnt figure out how to pass that data back just stored in a variable. Does anyone know how i could do that? I really dont want to have to push all my results to the db and then make a query for them. I want to have a save article function that you only save the ones you actually want.
I would really appreciate any help you might have, Im not very good at all this yet!
Thank you in advance
-
updating user details MEAN stack
Im stuck at updating a user profile, I've tried the solution on Can't update user with PUT Request in Angular 2 but it doesn't seem to work, perhaps its starting at me in the face but I can't seem to figure it out.
On my auth.service.ts I have this
updateDetails(id) { let headers = new Headers(); this.loadToken(); headers.append('Authorization', this.authToken); headers.append('Content-Type', 'application/json'); return this.http.put('http://localhost:3000/api/admin/' + id, this.user { headers: headers }) .map(res => res.json()); }
Then on client-edit.component.ts I have
updateUser(id) { this.authService.updateDetails(id).subscribe(res => { this.router.navigate(['/client-details', id]); }, (err) => { console.log(err); })
the user.js file has
router.put('/admin/:id', function(req, res, next) { User.findByIdAndUpdate(req.params.id, req.body, function (err, post) { if (err) return next(err); res.json(post); }); });
And finally the client-edit.component.html has
<form (ngSubmit)="updateUser(user._id)" ...... ...
Can anyone see where I've gone wrong, I don't get any errors in the console, I can see in the terminal that the put requests seem to be going through, but when I check it doesn't update at all.
Any insight to this I would really appreciate it.
Kind Regards, - P