Is it possible to accept POST request in vuejs (client-side)? - vue.js

The code below handles GET request and will display the login page:
const routes = [
{
path: '/',
name: 'root',
component: Login
}
]
I can display data using router with GET method in vuejs. Now, I want accept POST requests/methods from external website. Is it possible? If it is, how should I make it, if not possible, is there another alternative solution for this?

No, that's not possible. Your routes are not even GET requests. You can intercept any request on your own application, but you can't listen for external requests, that's what HTTP servers are for.

No, a client app in a browser cannot accept requests from other websites/services, no matter which HTTP method is going to be used.
If you want for some reason your Vue based application to be accessible remotely then you can consider using SSR.

Pass data via the webpage holding the Vue instance
Yes you can with a trick!
What is your first base file that is loading your vuejs ?
is this an html file like index.html?
try load your vuejs in a php file like index.php and at top of your php file like write this:
<!DOCTYPE html>
<html >
<head>
...
<script >
window.postedData = '<?php echo json_encode($_POST)?>';
</script>
...
</head>
Now you can use your postedData variable every where in your vuejs code
mounted() {
const arr=JSON.parse(postedData)
console.log(arr)
...
}

Related

how to force clearing cache in chrome when release new Vue app version

I created an app with vue-cli and then I build the dist folder for production.
The app is deployed on IIS with flask backend and works fine.
The problem occurs when I have to make some changes and I have to redo the deployment. After this, users call me because app doesn't work but if I clear the chrome cache, the app works fine again.
How can I fix this problem? Is there a method to clear chrome cache automatically when I release a new application version?
Thanks
my dist folder
deployment: copy and paste folder dist on IIS
if files in dist folder are correct, maybe the problem is in axios cache? i have make some changes also to rest apis
I had the same problem and changing (incrementing) the version number in package.json before running the build command fixed it.
For example by default the version number is set to "0.1.0"
package.json file:
{
"name": "project-name",
"version": "0.1.1",
"private": true,
...
}
If you use vue-cli, then it has built-in webpack configs for building dist. And in fact it adds hash-names to output files.
But if it was removed somehow, you can add it back to webpack config like
output: {
filename: '[name].[hash].bundle.js'
}
And your app will looks like this:
And even more, you do not need to handle how all this stuff will be added to html, coz webpack will figure it out for you.
You need to add a version query to your js file. This is how a browser can know if the file has changed and needs to download the new version.
So something like:
<script src="main.js?v=1.1"></script>
<script src="main.js?v=1.2"></script>
etc...
Assuming this is nothing to do with service worker/PWA, the solution could be implemented by returning the front-end version.
axiosConfig.js
axios.interceptors.response.use(
(resp) => {
let fe_version = resp.headers['fe-version'] || 'default'
if(fe_version !== localStorage.getItem('fe-version') && resp.config.method == 'get'){
localStorage.setItem('fe-version', fe_version)
window.location.reload() // For new version, simply reload on any get
}
return Promise.resolve(resp)
},
)
You can also ensure the fe-version is returned based on any sort of uniqueness, here I have used the commit SHA.
Full Article here: https://blog.francium.tech/vue-js-cache-not-getting-cleared-in-production-on-deploy-656fcc5a85fe
You can't access the browser's cache, that would be huge a security flaw.
To fix it, you must send some headers with your flask responses telling the browser not to cache you app.
This is an example for express.js for you to get the idea:
setHeaders: function (res, path, stat) {
res.set('Cache-Control', 'no-cache, no-store, must-revalidate') // HTTP 1.1
res.set('Pragma', 'no-cache') // HTTP 1.0
res.set('Expires', '0') // Proxies
}
You can read a lot more about caching in here.
This is an older post, but since I could not find the solution for this problem online, ill just post this here in case someone else might find it usefull.
I added the hash to the appllication chunk files via the webpack.mix.js file by adding:
mix.webpackConfig({
output: {
chunkFilename: 'js/[name].js?id=[chunkhash]',
},
})
This adds a fingerprint to the actual chunks and not just the app.js file. You can add a version name to the app.js file aswell by adding version(['public/js/app.js']); at the end of the file, or add filename: '[name].js?[hash]' to the output block.
My complete webpack.mix.js:
const mix = require('laravel-mix');
mix.webpackConfig({
output: {
chunkFilename: 'js/main/[name].js?id=[chunkhash]',
}
}).js('resources/js/app.js', 'public/js').vue()
.postCss('resources/css/app.css', 'public/css', [
//
]).version(['public/js/app.js']);
In my laravel blade file I used
<script src="{{ mix('js/app.js') }}"></script>
to load the app.js file with the correct version fingerprint.
The answer for me was caching at my DNS provider level.
Basically, I'm using Cloudflare DNS proxy and they are caching the website so in development mode I was not getting the code updates.
I had to clear the cache many times to get anything to change. I had to wait a significant period of time before anything update.
Turned it off and it stopped doing that.
the method I want to suggest
<script src="{{ asset('js/app.js?time=') }}{{ time() }}" defer></script>
add below script in publc/index.html
<head>
...
<script type="text/javascript" language="javascript">
var timestamp = (new Date()).getTime();
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "<%= BASE_URL %>sample.js?t=" + timestamp;
document.head.appendChild(script);
</script>
...
</head>
could you try ?
vm.$forceUpdate();
Also it's possible that the component it self needs a unique key :
<my-component :key="unique" />

How to remove Magento product details storage in browser?

In Magento 2 when we are opening multiple products it stores data of those products into window.localStorage.product_data_storage locally into the browser many of the browser that data get deleted automatically but in some of the browsers it is not getting deleted
I do have to say I opened about 200 products before this happened, but
it is never clear.
When we clear the cache of browser then it is removing that content of data from browser, but it is simply understood that the end user will not go to clear their cache every time so How we can remove this content from their browser?
Any Help will be appreciated
Thank You!
As of I understood that you wanted to remove the content from browser that Magento stores locally into every browser when you/anyone opens your site to use them at some places for example to maintain the component of knock-out js in magento like in checkout page, mini-cart, etc.
Here I have created a module to achieve this, with this module you can manage that how much content should be stored into the browsers local storage. Means the magento will store the content into local storage of browser but like if you want that data should be get deleted when the limit riches to 10-20 whatever the unit you wish Then the module will delete the content from the browser & magento will again start storing data to the local from 1 count to your desired limit.
Create a module at below location
Magento_root/app/code/{VendorName}/{ModuleName}
Create below files into it at the appropriate given location.
registration.php
etc/module.xml
view/frontend/layout/catalog_product_view.xml
view/frontend/templates/product/view/removelocal.phtml
view/frontend/web/js/removelocal.js
Here I am not putting the content of registration.php & module.xml assuming that it is already understood to you. For this answer I am taking the VendorName => Vendorname & the ModuelName => Removelocal. Here is the code of custom module.
catalog_product_view.xml
<?xml version="1.0"?>
<page layout="1column" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceContainer name="content">
<block class="Magento\Framework\View\Element\Template" name="vendorname.removelocal.content" template="Vendorname_Removelocal::product/view/removelocal.phtml" before="-" />
</referenceContainer>
</body>
</page>
removelocal.phtml
<div class="swatch-opt" data-role="remov-local-content"></div>
<script type="text/x-magento-init">
{
"[data-role=remov-local-content]": {
"Vendorname_Removelocal/js/removelocal": {
}
}
}
</script>
removelocal.js
define([
'jquery'
], function ($){
'use strict';
$.widget('mage.removelocal', {
_init: function () {
if(window.localStorage.product_data_storage)
{
var temp = window.localStorage.product_data_storage;
var myObject = JSON.parse(window.localStorage.product_data_storage);
var count = Object.keys(myObject).length;
if(count >= 10){
window.localStorage.removeItem('product_data_storage');
}
}
}
});
return $.mage.removelocal;
});
Note: After completing please do run the below command.
php bin/magento module:enable Vendorname_Removelocal
php bin/magento setup:upgrade
php bin/magento setup:static-content:deploy -f
php bin/magento cache:flush

Detect when reCaptcha does not load

What is the best way to detect if a reCaptcha v2 does not load? I would like to alert users when they need to use the captcha to continue, but it was unable to load.
You can pass a callback function when you make the request for the captcha
Add this to the url:
?onload=myfunction
for example:
<script src="https://www.google.com/recaptcha/api.js?onload=loadedCallback&render=explicit"
async defer>
</script>
Js:
function loadedCallback(){
//Recaptcha its loaded
}

How can I make Aurelia routing work when the application is not at the root of the host

I am building an Aurelia application that will not live at the root of the web site. Its URL will be something like this http://mycompany.com/neatoApp.
I have a route configuration that looks like this
{route:['','index'], name:'index',moduleId:'index' nave:true, title: 'neato app home'},
{route:['news'], name:'news',moduleId:'news' nave:true, title: 'neato app news'}
I have System.js configured so that it knows /neatoApp is the baseURL and it downloads all the scripts and things properly.
I have a <base href="/neatoApp" /> element in the head of my app html and I'm using pushState for routing.
The problem is when I navigate to mycompany.com/neatoApp Aurelia reports 'Route not found: /neatoApp'
Router has a baseUrl property that doesn't seem to matter what I set its value to because the route recognizer doesn't use it.
I really don't want to put neatoApp in all my routes for a few good reasons: As the app gets deployed in various places (dev, test, etc) that base path will change making that a headache to maintain. It's not the developers responsibility to know where the app is going to be deployed in various environments and it's not the operations guy's responsibility to update the code to include that base URL when he deploys it. When I do include neatoApp in the routing config it makes navigating behave strangely like generating a link that points to /neatoApp/neatoApp.
Does anybody have a solution to this problem?
I have created a plunker to demonstrate the issue: http://plnkr.co/edit/HPEzClAlncvQkSzjw6ph?p=preview
Check out this plunker to see what needs to be done:
http://plnkr.co/edit/0j6vhbTf4LZw4vOLOUka?p=preview
When you are doing something like a virtual directory where your site looks like this http://mywebsite/subfolder you want to preface your routes, stylesheets, and the baseURL in config.js to have "./" for example:
baseURL: "./"
And index.html would typically look like this:
<script src="./jspm_packages/system.js"></script>
<script src="config.js"></script>
Same with app.js which should look like this:
{ route: "", moduleId: "./src/routes/home", title: "Home", nav: true, name:"home" },
If you are publishing to the root of a web site then you can drop the "./" and just use "/" although technically you can leave the routes with "./" and just change the baseURL and it will still work.
For my MVC 5 app, I use this in my Index.cshtml:
<script src="~/jspm_packages/system.js"></script>
<script>
System.config({ baseURL: "#Url.Content("~/")" });
</script>
<script src="~/config.js"></script>
<script>
System.import('aurelia-bootstrapper');
</script>
And have commented out the baseUrl in config.js. BaseUrl needs to be set in the first call to System.config().
System.config({
//baseURL: "./",
defaultJSExtensions: true,
...

Redirect Express js piped (req.pipe) res properly

Probably I'm doing something wrong but:
In my browser I have a code
window.location = '/some/url'
or element with href="/some url"
in node (express.js) I have following route handler:
app.get('/some/url', function(req, res){
res.redirect('http://www.google.com')
});
Content of the page is loaded with strange flaw Google page. And address bar is not changed (http://localhost:3000/some/url).
I'm making request via intermediate server using
req.pipe(request(host + req.url)).pipe(res) and it seems that piped res does not redirect properly. Any ideas how to solve it?
I needed to use {folllowRedirect: false} option for reqest.js