Problem with Vue.JS to get content-disposition headers when deployed - vue.js

I'm facing a problem to get an header in axios to get the file name i want to download in vue.js when it was deployed on static web apps on azure but not in Local, in local it work...
Here is the code i use to get the filename in the header.
const headerLine = response.headers["content-disposition"];
const startFileNameIndex = headerLine.indexOf('"') + 1;
const endFileNameIndex = headerLine.lastIndexOf('"');
const filename = headerLine.substring(startFileNameIndex, endFileNameIndex);
The console throw me the error that "headerLine is undefinded"... In response headers i've the content-disposition header visible.
I don't understand why it doesn't work online.

Maybe you should check the server side, see this discussion: https://github.com/axios/axios/issues/895

Related

Vue3 app after logout throws CORS policy error

I have Vue3 app which makes requests with Axios. As I logout from the app and then login again app starts throwing error
create:1 Access to XMLHttpRequest at 'https://vue.tatrytec.eu/'
(redirected from 'https://tatrytec.eu/api/article/store') from origin
'https://vue.tatrytec.eu' has been blocked by CORS policy: Response to
preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource.
One thing I dont understand is that as I reload the page it starts working and error is gone. The code is still the same. How can reload has impact to the CORS error?
The app code for Axios is in this Github repository.
import axios from "axios"
window.axios = axios;
//axios.defaults.baseURL = apiRoutes.API_URL_SHORT;
axios.defaults.withCredentials = true;
axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
let authToken = localStorage.getItem('authToken');
axios.defaults.headers.common['Authorization'] = 'Bearer ' + authToken;
axios.defaults.headers.common['Access-Control-Allow-Origin'] = 'https://vue.tatrytec.eu';
Hope somebody knows cause I have no idea what happened there.
The problem was in the login form axios setting. There was this code
axios.defaults.headers.common = {
'Authorization': 'Bearer ' + token
};
I dont know where I found it but this garbage code rewrites whole common object in axios settings. So I lost all other headers. Really would like to know where I found this code. The proper style is to use array syntax like common['Authorization'] = ... Vrrrrr.

how to get browser full url of the page in nodejs express in environment, seems nginx issue?

I am using a url rewriting functionality in my application(SparatcusV3.4).
I am calling my backend from node js to check a productcode exists or not
for that I need the current browser url entered by user in the address bar.
I am accessing the url using below code
const fullUrl = req.protocol + '://' + req.get('host')
this is working fine on my local system but when deployed on any environment(by SAP)
this URL is coming as "127.0.0.1:4200" , what might be the problem here with environment ?
or what is the correct way to get the full browser url entered by the user ?
any help would be appreciated!!!
thanks in advance
Please refer to this part of Spartacus docs: https://sap.github.io/spartacus-docs/server-side-rendering-coding-guidelines/#getting-the-request-url-and-origin
It suggests to use SERVER_REQUEST_URL and SERVER_REQUEST_ORIGIN injection tokens when using the setup that's running SSR behind a proxy in order to resolve URLs.
To use these optional tokens:
it is assumed you're using Spartacus' NgExpressEngineDecorator from #spartacus/setup/ssr in your server.ts file.
when injecting them, you should mark them as #Optional (per docs), as these are not available in CSR application.
const obj = {};
const rc = request.headers.cookie;
rc?.split(';')?.forEach((cookie: any) => {
const parts = cookie?.split('=');
obj[parts.shift().trim()] = decodeURI(parts?.join('='));
});
return obj;
it can give list of all cookies in request object so with OBJ['RT'] can give the value and further splitting with '=' we cna get the exact request URL there from we can extract the host and the origin uding below code
const cookieName = 'RT';
const cookieObj = this.getCookieasObject(req);
let fullURL = cookieObj[cookieName];
if (fullURL) {
fullURL = decodeURIComponent(JSON.parse(fullURL).split('=')[1]);
}
const url = new URL(fullURL);
const baseUrl = `${url.protocol}//${url.hostname}`;

Cors issue solved by using proxy not working after served in Netlify Create-react-app

I have built a real estate site that makes a an api request to "https://completecriminalchecks.com" In development mode I was getting the dreaded blocked by Cors error. Through some research I found that I needed to use a proxy to solve the issue, which it did in development mode on my local host. But now I have deployed the site to netlify, I am getting a 404 error when making the request. when I look at the request from the network devtools its says
Request URL: https://master--jessehaven.netlify.app/api/json/?apikey=6s4xxxxx13xlvtphrnuge19&search=radius&miles=2&center=98144
I dont think this is right. How do i make netlify make the proper request to the api that was having cors issues in development?
Have you tried netify documentation about it?
Proxy to another service Just like you can rewrite paths like /* to
/index.html, you can also set up rules to let parts of your site proxy
to external services. Let's say you need to communicate from a
single-page app with an API on https://api.example.com that doesn't
support CORS requests. The following rule will let you use /api/ from
your JavaScript client:
/api/* https://api.example.com/:splat 200
Now all requests to /api/... will be proxied through to
https://api.example.com straight from our CDN servers without an
additional connection from the browser. If the API supports standard
HTTP caching mechanisms like ETags or Last-Modified headers, the
responses will even get cached by our CDN nodes.
You do not need to use a proxy, you enable CORRS in your server. Are you using a onde server?
If you use express something like this:
npm install --save cors
And then use it as middleware:
var express = require('express');
var cors = require('cors');
var app = express();
app.use(cors());
Also in your netlify.toml file this will do the trick:
# The following redirect is intended for use with most SPAs that handle
# routing internally.
[[redirects]]
from = "/*"
to = "/index.html"
status = 200
[[headers]]
# Define which paths this specific [[headers]] block will cover.
for = "/*"
[headers.values]
Access-Control-Allow-Origin = "*"
I also faced the same issue and solved by creating a netlify.toml file in root directory.
Here is a sample code for redirect which worked for me.
Place this inside the netlify.toml file.
Documentation guide for proxy :
[[redirects]]
from = "/api/users/tickets/"
to = "https://some-external-site.com/api/users/tickets/"
status = 200
force = true
headers = {Access-Control-Allow-Origin = "*"}
[[redirects]]
from = "/api/users/cars/*"
to = "https://some-external-site.com/api/users/cars/:splat"
status = 200
force = true
headers = {Access-Control-Allow-Origin = "*"}
I also faced the same issue , so I removed the "proxy" from the "package.json" file and created a variable to store the IP addess or URL for backend , then used it with the URL parameter for calling API. The CORS issue is solved in backend by allowing "All origins".
File to store base URL:
constant.js :
export const baseUrl = "https://backEndUrl";
File to call API:
getDataApi.js:
import { baseUrl } from "./constant";
export const getProfileData = () => (dispatch) => {
axios
.get(`${baseUrl }/api/profile`)
.then((res) =>
dispatch({
type: GET_PROFILE,
payload: res.data,
})
)
.catch((err) =>
dispatch({
type: GET_PROFILE,
payload: null,
})
);
};

serving static json data with question mark in filename in expressjs

I am attempting to to serve json data statically from the filesystem in order to mock an api.
I was using deployd in my stack before and able to serve /users/names?id=123 from ./users/names?id=123/index.html, but I wanted to remove that dependency and just rely on express like so:
var express = require('express'),
cors = require('cors'),
app = express();
app.use(cors());
app.use(express.static('api'));
app.listen(3000, function () {
console.log('API Mock Server listening on port 3000!');
});
Unfortunately express is not serving the JSON file when i access it at ./users/names?id=123/index.html, I also tried renaming that index.html to: ./users/names?id=123 to no avail
You should percent encode the '?' when you access it in your browser.
so try ./users/names%3Fid=123/index.html
See File URI encoding rules.

XmlHttpRequest origin header is null in webkit

I am trying to integrate 2 webapps to let one (new one) send a url to another (old one) that it will load into a text area. The URL is actually to a file in S3 (with the multiple redirects that come with that) and I am trying to do this in the receiver using an XMLHTTPRequest like so;
var client = new XMLHttpRequest();
client.withCredentials = true;
client.open('GET', geneIdFileUrl, true );
client.setRequestHeader("Content-type", "text/plain");
client.onreadystatechange = function() {
document.getElementById('geneList').value = client.responseText;
}
client.send();
This is fine in firefox but in webkit browsers (chrome, safari) the request is being sent out with the request header
Origin null
instead of the real origin of the page making the request. The get from S3 is coming as a ContentDisposition attachment so I can't just dump it into an iframe and read the contents from there.
Why do the webkit browsers not set the origin properly and is it possible to coecre them into doing so?