Assuming a Feathers app with the following directory structure:
- src
-- hooks
-- middleware
-- services
Where is an appropriate place to put webhook route handlers? Should this be done using middleware, or would it be more idiomatic to use standard Express routes and put them within a routes directory?
For context, I want to listen to events from Instagram, and they don't necessarily match up with the RESTful services I'm using.
A middleware is only a handler for a standard express route. I'd consider a webhook a middleware like any other non-service endpoint.
In that middleware you can retrieve services via req.app.service. For example an Instagram webhook that creates entries in the images service for the data retrieved by the webhook and then sends the status (or error back) can look like this:
app.use('/instagram', function(req, res) {
const imageService = req.app.service('images');
const images = req.body.data;
imageService.create(currentData).then(() => {
res.status(200);
res.end('ok');
}).catch(error => {
res.status(500);
res.end(error.message);
});
});
The data sent to the webhook should also be verified with Instagram before adding them to the database.
Related
I have a node.js server running and is executing what I want it to do, create an excel document with data fetched with Axios from an API, now, I want to allow a user to input a string on my HTML and then send that string to my web server, and perform an Axios request to the API that I am consuming. How can I do that? Should I use a POST request, a PUT request, or anything else?
Thanks!
You should be able to send data from your client to the server via the request body regardless of the request method whether GET/POST/PUT.
fetch call would look like this
// just a simple get request
fetch('/example-endpoint', {
method: 'POST',
body: {
data: 'String to be sent'
}
});
And on your node express server
app.post('/example-endpoint', (req, res) => {
const data = req.body.data;
// do stuff with your data here.
})
GET request method is used for getting data, while POST and PUT are used for creating and updating data, so use them as you need them.
POST request to your server, like uh https://myserver.com/api/${userString}
something like that
I have an API which is working fine on Postman and getting a result when I provided the email and password in the header section ,now I have a login form and I want to authenticate the user from that API data result if the user name and password matched with API data then logged in otherwise show error. This type of work I wanted but I am very confused where to start it.and I only want to use es6 functions.
You create a login function that makes an ajax call to your API, probably using the fetch API (or some other ajax library like Axios). Your call returns a promise, with the result from the server, which you then act upon.
const login = (formValues) => {
return fetch('/your/api/url', {
method: 'POST',
body: JSON.stringify(formValues)
})
.then((response) => JSON.parse(response))
.then((data) => {
// do something with the server data
})
.catch((error) => {
// do something with the error
});
};
That's the gist. Your server may require additional request parameters, so review the API for whatever ajax method you choose. Again, there are libraries like Axios that can abstract/simplify/expand the fetch API for you, or you can just use it directly. Biggest thing to remember is that you can't access the return values until you actually have them, so if you are unfamiliar with Promises then you should also study up on them.
Using Fetch
Promise
The answer for Node.js - How to send data from html to express solves the problem I have by using a different port for the server. I was wondering how live websites for example this website (stackoverflow's search bar) use a form action that is a directory ("/search") instead of a port similar to the answer at the link? Is node.js incapable of listening to a directory or am I ignorant when it comes to how http requests work?
You listen on a port for http requests. Your front end will do an ajax(asynchronous javascript and xml) request in your javascript code to a route on your server through a port.
If you want a good tool for making easy ajax requests, you can use jQuery, or Axios, and look up how to do ajax with those libraries.
On the back end your server is listening to a port for requests to routes. Set up a route(what you've called a directory) to respond to requests to a particular URL. The example you mentioned showed:
app.post('/myaction', function(req, res) {
res.send('You sent the name "' + req.body.name + '".');
});
Express is a backend framework for doing all kinds of things, but most commonly, handling HTTP requests and rendering HTML. So on the front end when you make your ajax request to /myaction, you can respond like this:
app.post('/myaction', function(req, res) {
res.render('templateFileToRender', { dataToDynamicallyTurnIntoHTML: data } );
});
Express will render your template file, then send the HTML to your front end, and you will update your frontend div or whatever with the rendered HTML.
If you want more info please leave a comment
I think I'm having an issue passing a session from my Node backend to my React frontend, but I'm in kind of an I don't know what I don't know situation. Can anyone help?
Here's the issue:
I've got this route on the backend..
app.get('/account', ensureAuthenticated, function(req, res){
res.status(200).json({ user: req.user });
});
which spits out userdata JSON upon a successful Steam Passport authentication. I can verify this works when I check the account page generated by EJS views.
On the React server, I have a root page with a link to Steam auth. It successfully goes to Steam, then redirects back to the root page.
When I try to do a JSON fetch to '/account' from the root React page, the response is no longer JSON, but is HTML from the backend's '/account' template, but I need JSON of course.
I think it's not recognizing me as authenticated, because I get the same HTML response when doing a GET request using Chrome's Advanced REST client extension.
I should also note that I'm proxying the API server via Create React App's proxy feature.
UPDATE: Problem solved.
fetch('https://example.com:1234/users', {
credentials: 'include'
})
It sounds like the issue may be due to the order of app.get calls, or the configuration of your node server – likely the EJS templates.
I would look for where you're doing something like app.set('view engine', 'ejs'); and where you're doing app.get('/account'....
You'll want to do the app.get('/account'.. before you do app.set('view engine...
If you actually hit the /account route you should get either a 401 or the JSON response, not HTML (EJS).
I am still a bit new about AngularJS and just came across the topics about service, provider, and factory.
I have still problem(s) on:
How to load JSON response from server via REST.
Place the loading code in either service, provider, factory in which suits it best.
Provide encapsulation feature (getters/setters) in which $scope could watch the changes if the load was successful or not.
Please comment for clarifications.
The RESTful functionality is provided by Angular in the ngResource module.
It's better to use $http service for non restful resources
var phonecatServices = angular.module('phonecatServices', ['ngResource']);
phonecatServices.factory('Phone', ['$resource',
function($resource){
return $resource('phones/:phoneId.json', {}, {
query: {method:'GET', params:{phoneId:'phones'}, isArray:true}
});
}]);
The $resource service makes it easy to create a RESTful client with
just a few lines of code. This client can then be used in our
application, instead of the lower-level $http service.
Please check this link for additional details
https://docs.angularjs.org/tutorial/step_11