serving static json data with question mark in filename in expressjs - express

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.

Related

Express Set Custom Parameter Query Starter

I'm using express to interact with discord's oauth2 api.
When I request a user oauth token the server responds with a url like:
http://localhost:3000/index#token_type=Bearer&access_token=tkn&expires_in=int
I'm trying to extract the parameters after the # as with discords api parameters start with # unlike others which start with a ?
Because it doesn't start with a question mark I am unable to use the req.params.x property.
I thought, "No big deal, ill just get the url and extract it myself" but every single url accessor in express removes string after #. This includes req.url and req.originalUrl which both return the file path.
So how can I get url parameters started by hashtags instead of question marks?
Or How can I get the full url with content after hashtags
I was able to solve this problem by setting a custom query parser. Code snippet below.
const app = express();
app.set('query parser', (query) => {
return query.split('&').map(item => {
const [key, value] = item.split('=');
return {
key,
value
}
});
});
app.get('/', (req, res) => {
console.log(req.originalUrl); // Full URL starting with file path
})

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,
})
);
};

Vue Cli 3 blocks CORS even after headers change

I'm running locally both a Vue Cli 3 app and a Google Cloud Function (CF).
I have changed the response headers in CF as follows:
res.set('Access-Control-Allow-Origin', "*")
res.set('Access-Control-Allow-Methods', 'GET, POST')
and it serves me well when I call the CF from a browser.
For some reason, the same call is CORS blocked when invoked inside the Vue app.
I tried with Firefox (CORS enabled by settings as well as using a plugin).
I also added the following to vue.config.js as described here:
// vue.config.js
module.exports = {
devServer: {
proxy: 'http://localhost:8010', //<-- my CFs are running on 8010
}
}
Not sure how to proceed as the whole point of CFs is to not have any servers running (including a proxy).
Any pointers are much appreciated, cheers.
Problem was with the local Cloud Function emulator.
Got it working when I altered the Cloud Function headers in the live environment.
// Set CORS headers for preflight requests
function setCorsHeaders(req, res){
res.set('Access-Control-Allow-Origin', CLIENT_URL);
res.set('Access-Control-Allow-Credentials', 'true');
if (req.method === 'OPTIONS') {
// Send response to OPTIONS requests
res.set('Access-Control-Allow-Methods', 'GET,POST');
res.set('Access-Control-Allow-Headers', 'Content-Type');
res.set('Access-Control-Max-Age', '3600');
res.status(204).send('');
}
}

Node express server, CORS API restriction, including an entry in my development machine’s hosts file

I am trying to use an API that has an API CORS policy that does not support browser requests from any domain. In order to allow clientside JavaScript code to access the API, whilst developing my application, I have been advised to I serve my webapp from '*.thisCompany.com' domain.
It was advised to include an entry in my development machine’s hosts file, as follows, which I have done:
$ echo '127.0.0.1 localhost.thisCompany.com' >> /etc/hosts
Following this command when I run sudo nano /private/etc/hosts
this is the screen that I see.
Host Database
localhost is used to configure the loopback interface
when the system is booting. Do not change this entry.
127.0.0.1 localhost
127.0.0.1 localhost.thisCompany.com
And then I have been told that I should be able access my webapp at http://localhost.thisCompany.com.
I am using node express as my server and the code in my server.js file looks like this
var express = require('express');
var server = express();
var path = require('path');
var port = process.env.PORT || 'thisCompany.com';
server.use(express.static(__dirname + '/public'));
server.use('/bower_components', express.static(__dirname + '/bower_components'));
server.get('/', function(request, response) {
response.sendFile(path.join(__dirname + '/views/index.html'));
});
server.listen(port, function() {
console.log("Node app is running at localhost:" + port)
});
Can anyone advise what steps I should follow to enable me to call this API and bypass the API CORS policy?
I have read various other posts here, and also other articles online, however I cannot find the solution. Really hoping someone on this can help.
Thanks, Paul
I misunderstood how I was supposed to view a page locally on my computer after amending the hosts file on my local machine. I didn't need to add anything to my express server. The express server code remained as follows:
var express = require('express');
var server = express();
var path = require('path');
var port = process.env.PORT || 3000;
server.use(express.static(__dirname + '/public'));
server.use('/bower_components', express.static(__dirname + '/bower_components'));
server.get('/', function(request, response) {
response.sendFile(path.join(__dirname + '/views/index.html'));
});
server.listen(port, function() {
console.log("Node app is running at localhost:" + port)
});
After adding the line mentioned in my original post to my hosts file on my local machine, I then needed to launch my server and access the page by following this link.
http://localhost.thisCompany.com:3000/
Although this is quite a niche issue, I hope this post helps someone in the future.