How to authenticate a user in es6 while data coming from API? - ecmascript-6

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

Related

Chrome extension, how to track each visited page?

I wanted to build a Google Chrome extension that would display domain popularity, the way Alexa domain stats did;
I am able to display any data inside popup.html when user clicks my extension button (to show domain rank, backlinks, etc) but in background I need to track popular urls visited by users.
Using manifest v3, I was able (inside background.js) to detect and trigger code on each url change, but I cannot find a function that would allow the extension to ping my servers in order to tell what url/domain is visited by user.
I assume best way to do this is to make an URL get request in background. How can I do something like that ? Basically I want the extension to send a text message to an url of mine.
As wOxxOm mentioned you can use built in fetch API. As mentioned in this documentation, you can use fetch like this -
fetch(your_url, fetchParams) //fetch returns promise, that resolves to a response object
.then(response => response.json()) //assuming JSON response
.then(data => console.log(data))
.catch(err => console.error(err));
where fetchParam is typically a javascript object that follows the documentation mentioned above. you can add your custom data in the fetchParam's body key. like this
fetchParam = {
method: your_metod,
headers: your_header_object,
body: your_data
};
Hope I understood the question correctly.

How can I send data (string) from my html to my server (node or express) and execute certain function with it?

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

Yii When using PageCaching in ajax call not working

I was trying to implement page caching in Yii2 advanced project and everything seemed to be super cool. And suddenly I was hit by a strange issue.
Case: On the homepage of the website there is some dynamic data like showing records from DB, info of current user like the name (if the user is logged-in) and some static content. Also, a search input field which fetches result using AJAX call.
To speed page loading I implemented PageCaching provided by Yii2. And all worked good. But one issue I got stuck at is that after user log-in the ajax call didn't work and gave Error:
Bad Request (#400): Unable to verify your data submission.
I get this error till cache is refreshed after the set duration or I disable cache.
Is this issue related to cookie/session or something else? How to resolve it?
The 400 Bad Request is because the csrf-token is not being sent, with the request which is required to prevent cross-site attacks by Yii whenever you use POST to submit a page or ajax request, if you create an ActiveForm then it creates an input automatically with the token value.
You didn't add the code that you are using for the ajax call so not clear if you are using it for only one field or the whole form, so I would suggest the concerning part only.
You need to send the csrf-token and you can get it via javascript using yii.js and calling these 2 methods
yii.getCsrfParam() to get the parameter name of the token
yii.getCsrfToken() to get the token or actual value of the csrf-token
The csrfParam name is configured inside your frontend/config.php or config/web.php depending on the app you are using (advance /basic) under the request component like below
'components'=>[
......
......
'request' => [
'csrfParam' => '_csrf-frontend',
],
......
......
]
So what you need to do is either change the request method from POST to GET and send data via query string or use the following way to send the POST request.
Note: You should change the URL and add the csrf data into your existing data that you are sending with the request
let data={};
data[yii.getCsrfParam()]=yii.getCsrfToken();
$.ajax(
{
method:"POST",
url:"/site/test",
data:data,
success:function(data) {
console.log(data);
},
error:function(jqXHR,textStatus,errorThrown) {
console.log(jqXHR,textStatus,errorThrown);
}
}
);
If you have a test action inside the SiteController with the following code, then the above ajax call should show you the $_POST array inside the console with the csrf param and token value as key=>value.
public function actionTest()
{
print_r($_POST);
}

Instead of JSON response to POST request, what are my options for React?

Client-side I have a <form method="POST" action="/register"> which makes an SQL query.
Server-side I have this:
router.post('/register', function (req, res, next) {
// code [...]
if (!errors.isEmpty()) {
res.render('register', {
title: 'Registration Error',
errors: errors.mapped()
});
}
}
OK cool, with ejs I have managed to work with the incoming variable errors which is invisible (see next sentence) but my goal is to switch to React. Now, instead of the variable errors I have managed to send a json, but this json appears in the Developer Tools -> Network tab.
I've noticed that third party websites are using POST method with React and I don't see any json in the network tab, so it's either hidden or they use a different method.
Instead of JSON response to POST request, what are my options for React (or if I can hide it)?
If you want to handle the response of a (POST) request in React (or JavaScript) you'll need to send the request via fetch or xhr.
Fetch: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
XHR: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest

Where to implement webhook routes in a feathersjs app?

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.