CORS policy in vue.js. Access only in backend? - javascript

If I have project in vue-cli with no node.js (or express.js), can I somehow unblocke this CORS access?
I tried to add a code in vue.config.js
vue.config.js:
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://18.700.121.3:8000/',
ws: true,
changeOrigin: true
}
}
}
}
vue template
import axios from 'axios'
export default {
name: "Jokes",
data () {
return {
songs: null,
}
},
},
mounted () {
const config = {headers: {'Access-Control-Allow-Origin': '*'}};
axios
.get(`http://2.788.121.2:4000/`, config) //it a sample api
.then(
response => (
this.songs= response.data))
}
}
</script>
but it didn't help. Also I tried to swich-on chrome plugin Access-Control-Allow-Origin, where I add access to localhost:8080, but still doesnt work.
So it is possible, that only option is install node.js and add res.header("Access-Control-Allow-Headers","*");

Try remove the header const config = {headers: {'Access-Control-Allow-Origin': '*'}}; from the request
The additional header will just confuse the browser

First way,
Use Cors Plugin in chrome Eg- Moseif CORS or Degrade your chrome version less than 71.
Second way, If you can modify the server-side code (If using express)
Add below codes, You can easily solved this problem.
var cors = require('cors')
var app = express()
app.use(cors())

Close the Chrome.
Hold down the Windows Key and Press R on your keyboard. The "RUN" dialog box will open.
Insert the following input field chrome --disable-web-security --user-data-dir and run it
Now run your vue.js app
Hope it helps.

Related

Proxying requests from React to External REST API

I'm working on a website made with React, run with npm. The website currently uses a JS API run with the website code, but we're migrating to using an external REST API. Everything's configured correctly to run locally with a webpack dev server:
proxy: {
'/apiv1': 'http://localhost:5000/', // in prod, run in the same container
'/api': {
target: 'http://localhost:8080/', // in prod, run separately on a different url (api.website.com)
pathRewrite: { '^/api/': '' },
},
},
In the console, I see errors complaining that some data is undefined (using the minified variable names, so difficult to track down--but almost certainly data from the API).
I checked if it was a CORS issue per this question, but I'm still having the same issue with CORS disabled completely.
I can successfully ping the api with a direct request, placed at the beginning of the base App's render method:
axios.get("https://api.website.com/")
I've tried to add the following to my package.json per this:
"homepage": ".",
"proxy": {
"/api": {
"target": "https://api.website.com",
"pathRewrite": {
"^/api": ""
},
"changeOrigin": true
}
},
In general -- how can I proxy requests for website.com/api/request to api.website.com/request in production? Is there something else I'm configuring incorrectly?
Please let me know if there's any more information I can add!
Edit:
I've also tried configuring the proxy with http-proxy-middleware:
// src/setupProxy.js
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function (app) {
app.use(
'/api',
createProxyMiddleware({
target: "https://api.website.com",
pathRewrite: {
"^/api": ""
},
changeOrigin: true,
})
);
};
Proxying api requests in production for React/Express app
In production we can't use (proxy).. instead we can set a variable in the frontend for the backend URL, and vise versa.
https://github.com/facebook/create-react-app/issues/1087#issuecomment-262611096
proxy is just that: a development feature. It is not meant for production.
These suggest that it's entirely impossible. Makes sense that the proxy option won't work, but I can't say I understand why there's no equivalent functionality for a production environment. It seems the best option for me is making all calls to the full domain instead of proxying.
If you're using nginx, the linked answers suggest using that to proxy the requests:
upstream backend-server {
server api.example.com;
}
server {
listen 80;
server_name example.com;
root /var/www/build;
index index.html;
location /api/ {
proxy_pass http://backend-server;
}
location / {
try_files $uri /index.html;
}
}

Vite react proxy sends requests to different endpoints depending on current location

After switch to vite, I am trying to mimic proxy: "http://localhost:5000" which I previously used in package.json
Here is my vite config
export default defineConfig({
plugins: [react()],
server: {
proxy: {
"/api": {
target: "http://localhost:5000",
changeOrigin: true,
secure: false,
},
},
},
});
I have react app running on port 3000. When I send a request in the root url (http://localhost:3000) everything works fine
const { data } = await axios.get("api/user/me");
Well, not really fine. Even though proper data is returned in response, in the console request gets sent to http://localhost:3000/api/user/me instead of http://localhost:5000/api/user/me. Can anyone explain this behaviour?
The main problem is that when I navigate to another page (e.g. http://localhost:3000/dashboard), then the same request gets sent to http://localhost:3000/dashboard/api/user/me.
What am I doing wrong? I want to send requests to http://localhost:5000, no matter the location
I found a workaround by specifying FE url before every request const { data } = await axios.get("http://localhost:3000/api/user/me");, but still is there a way to mimic package.json proxy behaviour?
I resolved the issue by changing axios defaults
axios.defaults.baseURL = `http://localhost:5000`
By doing this I achieved what I was going for. Requests get sent to the proper endpoint no matter the location
I solved this problem by using Axios.
Create a new file. I called mine emailApi.
Setup your axios, like so:
export const emailApi = axios.create({baseURL: "http://localhost:<yourPortNumber>"})
Done! Whenever you want to send a request to your server, import the emailApi and you're good.
Also in your server, make sure to install cors and set it as a middleware, like so:
express().use(cors({origin: <viteLocalServer>}))

Not able to set proxy port in my vue js app

I am working on a web app using vue.js as a UI and node.js as server. Vue is running on port 8080 and Node.js is running on 3001, so to to make API calls I am using a proxy which is not working as expected.
The below code in my vue.config.js is used for the proxy:
module.exports = {
devServer: {
proxy: {
'^/api': {
target: 'http://localhost:3001',
ws: true,
secure: false
}
}
}
}
And below is my Home page file which will call the URL using axios
import axios from 'axios'
export default {
data () {
return {
categories: []
}
},
created () {
axios.get('/api/v1/categories')
.then(res => {
debugger
this.categories = res.data
})
}
}
As I am a new to vue.js, I don't know what is going wrong.
EDIT
This is the error I am getting:
Proxy error: Could not proxy request /api/v1/categories from localhost:8080 to http://localhost:3001/.
See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (ECONNRESET).
I encountered this problem, solved it by replacing localhost with 127.0.0.1, then with [::1]
A few months later, i had to go back to 127.0.0.1…
Maybe did some process change my hosts file.
You should type ping localhost in your terminal in order to check your current configuration and use the result to set your proxy.
Try this
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://localhost:3001',
ws: true,
secure: false
}
}
}
}
Also, check whether you have set a base path for axios. If so, please remove api from the axios call since base path will also get added to the axios call.

Method PATCH is not allowed by Access-Control-Allow-Methods in preflight response

I am using axios PATCH method in ReactJS to update the record but its getting failed with following error
Failed to load http://192.168.99.100:8080/adslots/883: Method PATCH is not allowed by Access-Control-Allow-Methods in preflight response.
Here is my action:
export const UPDATE_AD_SLOTS_REQUEST = 'UPDATE_AD_SLOTS_REQUEST';
export const UPDATE_AD_SLOTS_SUCCESS = 'UPDATE_AD_SLOTS_SUCCESS';
export const UPDATE_AD_SLOTS_ERROR = 'UPDATE_AD_SLOTS_ERROR';
export function updateAdslotsRequest(){
return {
type: UPDATE_AD_SLOTS_REQUEST
}
}
export function updateAdslotsSuccess(data){
return {
type: UPDATE_AD_SLOTS_SUCCESS,
data: data
}
}
export function updateAdslotsError(errors){
return {
type: UPDATE_AD_SLOTS_ERROR,
erros: errors
}
}
export function updateAdslots(data, id) {
return dispatch => {
dispatch(updateAdslotsRequest());
return axios.patch(`http://192.168.99.100:8080/adslots/${id}`, data)
.then(res => {
dispatch(updateAdslotsSuccess(res.data));
})
.catch(errors => {
dispatch(updateAdslotsError(errors));
})
}
}
I am totally confused.
The api you are making the call to has to allow PATCH requests. They can do this by setting the Access-Control-Allow-Methods header to also have Patch in it. Look up how to do this with whatever server side language your api is using. You could also maybe try switching your call to a POST request but that is more of a temporary fix.
I think it is problem related to CORS settings on your backend. You have to allow PATCH requests in CORS settings. What kind of backend server are you using?
Try this solution:
Go to your app.js file where you've defined all the middleware.
Open terminal and type command "npm install cors", and hit enter.
Now write the following code in your file:
const cors = require("cors");
const app = express();
app.use(cors());
Hopefully, It will do the trick!
You can use any cors extension/plugin to make it work in browsers.
Also, make sure u have configured extension settings sometimes PATCH requests are not listed down in extension settings
Happy to help !
workaround : use browserplugin CORS (chrome)
when cors is activated you can open cors options and add localhost:3000 to the whitelist.
Then this thing is working for me

Enabling CORS in Cloud Functions for Firebase

I'm currently learning how to use new Cloud Functions for Firebase and the problem I'm having is that I can't access the function I wrote through an AJAX request. I get the "No 'Access-Control-Allow-Origin'" error. Here's an example of the function I wrote:
exports.test = functions.https.onRequest((request, response) => {
response.status(500).send({test: 'Testing functions'});
})
The function sits in this url:
https://us-central1-fba-shipper-140ae.cloudfunctions.net/test
Firebase docs suggests to add CORS middleware inside the function, I've tried it but it's not working for me: https://firebase.google.com/docs/functions/http-events
This is how I did it:
var cors = require('cors');
exports.test = functions.https.onRequest((request, response) => {
cors(request, response, () => {
response.status(500).send({test: 'Testing functions'});
})
})
What am I doing wrong? I would appreciate any help with this.
UPDATE:
Doug Stevenson's answer helped. Adding ({origin: true}) fixed the issue, I also had to change response.status(500) to response.status(200) which I completely missed at first.
There are two sample functions provided by the Firebase team that demonstrate the use of CORS:
Time server with date formatting
HTTPS endpoint requiring Authentication
The second sample uses a different way of working with cors than you're currently using.
Consider importing like this, as shown in the samples:
const cors = require('cors')({origin: true});
And the general form of your function will be like this:
exports.fn = functions.https.onRequest((req, res) => {
cors(req, res, () => {
// your function body here - use the provided req and res from cors
})
});
You can set the CORS in the cloud function like this
response.set('Access-Control-Allow-Origin', '*');
No need to import the cors package
For anyone trying to do this in Typescript this is the code:
import * as cors from 'cors';
const corsHandler = cors({origin: true});
export const exampleFunction= functions.https.onRequest(async (request, response) => {
corsHandler(request, response, () => {
//Your code here
});
});
One additional piece of info, just for the sake of those googling this after some time:
If you are using firebase hosting, you can also set up rewrites, so that for example a url like (firebase_hosting_host)/api/myfunction redirects to the (firebase_cloudfunctions_host)/doStuff function. That way, since the redirection is transparent and server-side, you don't have to deal with cors.
You can set that up with a rewrites section in firebase.json:
"rewrites": [
{ "source": "/api/myFunction", "function": "doStuff" }
]
No CORS solutions worked for me... till now!
Not sure if anyone else ran into the same issue I did, but I set up CORS like 5 different ways from examples I found and nothing seemed to work. I set up a minimal example with Plunker to see if it was really a bug, but the example ran beautifully. I decided to check the firebase functions logs (found in the firebase console) to see if that could tell me anything. I had a couple errors in my node server code, not CORS related, that when I debugged released me of my CORS error message. I don't know why code errors unrelated to CORS returns a CORS error response, but it led me down the wrong rabbit hole for a good number of hours...
tl;dr - check your firebase function logs if no CORS solutions work and debug any errros you have
Updated answer: using cors library with Typescript support:
install cors
npm i -S cors
npm i --save-dev #types/cors
index.ts:
import * as cors from "cors";
const corsHandler = cors({ origin: true });
// allow cors in http function
export const myFunction = functions.https.onRequest((req, res) => {
corsHandler(req, res, async () => {
// your method body
});
});
Old answer:
(not working anymore)
Found a way to enable cors without importing any 'cors' library. It also works with Typescript and tested it in chrome version 81.0.
exports.createOrder = functions.https.onRequest((req, res) => {
// browsers like chrome need these headers to be present in response if the api is called from other than its base domain
res.set("Access-Control-Allow-Origin", "*"); // you can also whitelist a specific domain like "http://127.0.0.1:4000"
res.set("Access-Control-Allow-Headers", "Content-Type");
// your code starts here
//send response
res.status(200).send();
});
I have a little addition to #Andreys answer to his own question.
It seems that you do not have to call the callback in the cors(req, res, cb) function, so you can just call the cors module at the top of your function, without embedding all your code in the callback. This is much quicker if you want to implement cors afterwards.
exports.exampleFunction = functions.https.onRequest((request, response) => {
cors(request, response, () => {});
return response.send("Hello from Firebase!");
});
Do not forget to init cors as mentioned in the opening post:
const cors = require('cors')({origin: true});
Update: Any response function that takes time risk a CORS error with this implementation because this doesn't have the appropriate async/await. Don't use outside of quick prototyping endpoints that return static data.
This might be helpful.
I created firebase HTTP cloud function with express(custom URL)
const express = require('express');
const bodyParser = require('body-parser');
const cors = require("cors");
const app = express();
const main = express();
app.post('/endpoint', (req, res) => {
// code here
})
app.use(cors({ origin: true }));
main.use(cors({ origin: true }));
main.use('/api/v1', app);
main.use(bodyParser.json());
main.use(bodyParser.urlencoded({ extended: false }));
module.exports.functionName = functions.https.onRequest(main);
Please make sure you added rewrite sections
"rewrites": [
{
"source": "/api/v1/**",
"function": "functionName"
}
]
Simple solution using the Google Cloud Console Dashboard:
Go to your GCP console dashboard:
https://console.cloud.google.com/home/dashboard
Go to menu
"Cloud Functions" ("Compute" section)
Select your cloud function, e.g. "MyFunction", a side menu should appear on the right showing you the access control settings for it
Click on "Add Member", type in "allUsers" and select the role "Cloud Function Invoker"
Save it -> now, you should see a remark "Allow unauthenticated" in the list of your cloud functions
Access is now available to everybody from the internet with the correct config to your GCP or Firebase project. (Be careful)
If you don't/can't use cors plugin, calling the setCorsHeaders() function first thing in the handler function will also work.
Also use the respondSuccess/Error functions when replying back.
const ALLOWED_ORIGINS = ["http://localhost:9090", "https://sub.example.com", "https://example.com"]
// Set CORS headers for preflight requests
function setCorsHeaders (req, res) {
var originUrl = "http://localhost:9090"
if(ALLOWED_ORIGINS.includes(req.headers.origin)){
originUrl = req.headers.origin
}
res.set('Access-Control-Allow-Origin', originUrl);
res.set('Access-Control-Allow-Credentials', 'true');
if (req.method === 'OPTIONS') {
// Send response to OPTIONS requests
res.set('Access-Control-Allow-Methods', 'GET,POST','PUT','DELETE');
res.set('Access-Control-Allow-Headers', 'Bearer, Content-Type');
res.set('Access-Control-Max-Age', '3600');
res.status(204).send('');
}
}
function respondError (message, error, code, res) {
var response = {
message: message,
error: error
}
res.status(code).end(JSON.stringify(response));
}
function respondSuccess (result, res) {
var response = {
message: "OK",
result: result
}
res.status(200).end(JSON.stringify(response));
}
If there are people like me out there: If you want to call the cloud function from the same project as the cloud function it self, you can init the firebase sdk and use onCall method. It will handle everything for you:
exports.newRequest = functions.https.onCall((data, context) => {
console.log(`This is the received data: ${data}.`);
return data;
})
Call this function like this:
// Init the firebase SDK first
const functions = firebase.functions();
const addMessage = functions.httpsCallable(`newRequest`);
Firebase docs: https://firebase.google.com/docs/functions/callable
If you can't init the SDK here is the essence from the other suggestions:
If you use firebase hosting and host in the default location, choose rewrites: https://firebase.google.com/docs/hosting/full-config#rewrites
Or use CORS like krishnazden suggested: https://stackoverflow.com/a/53845986/1293220
A cors error can occur if you don't catch an error in a function. My suggestion is to implement a try catch in your corsHandler
const corsHandler = (request, response, handler) => {
cors({ origin: true })(request, response, async () => {
try {
await handler();
}
catch (e) {
functions.logger.error('Error: ' + e);
response.statusCode = 500;
response.send({
'status': 'ERROR' //Optional: customize your error message here
});
}
});
};
Usage:
exports.helloWorld = functions.https.onRequest((request, response) => {
corsHandler(request, response, () => {
functions.logger.info("Hello logs!");
response.send({
"data": "Hello from Firebase!"
});
});
});
Thanks to stackoverflow users: Hoang Trinh, Yayo Arellano and Doug Stevenson
Only this way works for me as i have authorization in my request:
exports.hello = functions.https.onRequest((request, response) => {
response.set('Access-Control-Allow-Origin', '*');
response.set('Access-Control-Allow-Credentials', 'true'); // vital
if (request.method === 'OPTIONS') {
// Send response to OPTIONS requests
response.set('Access-Control-Allow-Methods', 'GET');
response.set('Access-Control-Allow-Headers', 'Content-Type');
response.set('Access-Control-Max-Age', '3600');
response.status(204).send('');
} else {
const params = request.body;
const html = 'some html';
response.send(html)
} )};
Changing true by "*" did the trick for me, so this is how it looks like:
const cors = require('cors')({ origin: "*" })
I tried this approach because in general, this is how this response header is set:
'Access-Control-Allow-Origin', '*'
Be aware that this will allow any domain to call your endpoints therefore it's NOT secure.
Additionally, you can read more on the docs:
https://github.com/expressjs/cors
Cloud Functions for Firebase v2
Cloud Functions for Firebase v2 now allow you to configure cors directly in the HTTP options. It works without the need for any 3rd party package:
import { https } from 'firebase-functions/v2';
export myfunction = https.onRequest({ cors: true }, async (req, res) => {
// this will be invoked for any request, regardless of its origin
});
Beware:
At the time of writing, v2is in public preview.
Only a sub-set of regions is currently supported in v2.
Function names are restricted to lowercase letters, numbers, and dashes.
You can use v1 and v2 functions side-by-side in a single codebase. For improved readability, update your imports to access firebase-functions/v1 or firebase-functions/v2 respectively.
I have just published a little piece on that:
https://mhaligowski.github.io/blog/2017/03/10/cors-in-cloud-functions.html
Generally, you should use Express CORS package, which requires a little hacking around to meet the requirements in GCF/Firebase Functions.
Hope that helps!
For what it's worth I was having the same issue when passing app into onRequest. I realized the issue was a trailing slash on the request url for the firebase function. Express was looking for '/' but I didn't have the trailing slash on the function [project-id].cloudfunctions.net/[function-name]. The CORS error was a false negative. When I added the trailing slash, I got the response I was expecting.
If You are not using Express or simply want to use CORS. The following code will help resolve
const cors = require('cors')({ origin: true, });
exports.yourfunction = functions.https.onRequest((request, response) => {
return cors(request, response, () => {
// *Your code*
});
});
Go into your Google Cloud Functions. You may have not seen this platform before, but it's how you'll fix this Firebase problem.
Find the Firebase function you're searching for and click on the name. If this page is blank, you may need to search for Cloud Functions and select the page from the results.
Find your function, click on the name.
Go to the permissions tab. Click Add (to add user).
Under new principles, type 'allUsers' -- it should autocomplete before you finish typing.
Under select a role, search for Cloud Functions, then choose Invoker.
Save.
Wait a couple minutes.
This should fix it. If it doesn't, do this AND add a CORS solution to your function code, something like:
exports.sendMail = functions.https.onRequest((request, response) => {
response.set("Access-Control-Allow-Origin", "*");
response.send("Hello from Firebase!");
});
If you're testing firebase app locally then you need to point functions to localhost instead of cloud. By default, firebase serve or firebase emulators:start points the functions to server instead of localhost when you use it on your web app.
Add below script in html head after firebase init script:
<script>
firebase.functions().useFunctionsEmulator('http://localhost:5001')
</script>
Make sure to remove this snippet when deploying code to server.
I got the error because I was calling a function that didn't exist on the client side. For example:
firebase.functions().httpsCallable('makeSureThisStringIsCorrect');
Adding my piece of experience.
I spent hours trying to find why I had CORS error.
It happens that I've renamed my cloud function (the very first I was trying after a big upgrade).
So when my firebase app was calling the cloud function with an incorrect name, it should have thrown a 404 error, not a CORS error.
Fixing the cloud function name in my firebase app fixed the issue.
I've filled a bug report about this here
https://firebase.google.com/support/troubleshooter/report/bugs
From so much searching, I could find this solution in the same firebase documentation, just implement the cors in the path:
import * as express from "express";
import * as cors from "cors";
const api = express();
api.use(cors({ origin: true }));
api.get("/url", function);
Link firebase doc: https://firebase.google.com/docs/functions/http-events
If you prefer to make a single handler function (reference answer)
const applyMiddleware = handler => (req, res) => {
return cors(req, res, () => {
return handler(req, res)
})
}
exports.handler = functions.https.onRequest(applyMiddleware(handler))
I'm a very beginner with Firebase (signed up 30 minutes ago). My issue is that I called my endpoint
https://xxxx-default-rtdb.firebaseio.com/myendpoint
Instead of
https://xxxx-default-rtdb.firebaseio.com/myendpoint.json
If you just started with Firebase, make sure you don't forget the .json extension.
I have been trying this for a long time.
It finally finally worked when I made this change.
app.get('/create-customer', (req, res) => {
return cors()(req, res, () => {
... your code ...
The Big difference is that I used cors()(req, res... instead of directly cors(req, res...
It Now works perfectly.
With the same access allow control origin error in the devtool console, I found other solutions with also more modern syntax :
My CORS problem was with Storage (and not RTDB neither the browser...), and then I'm not in possession of a credit card (as requested by the aforementioned solutions), my no-credit card solution was to :
install gsutil :
https://cloud.google.com/storage/docs/gsutil_install#linux-and-macos
to create a cors.json file to be loaded via terminal with gsutil
gsutil cors set cors.json gs://[ your-bucket ]/-1.appspot.com
https://firebase.google.com/docs/storage/web/download-files#cors_configuration
In my case the error was caused by cloud function invoker limit access. Please add allUsers to cloud function invoker. Please catch link. Please refer to article for more info
If none of the other solutions work, you could try adding the below address at the beginning of the call to enable CORS - redirect:
https://cors-anywhere.herokuapp.com/
Sample code with JQuery AJAX request:
$.ajax({
url: 'https://cors-anywhere.herokuapp.com/https://fir-agilan.web.app/gmail?mail=asd#gmail.com,
type: 'GET'
});
See below for how I set up my Express with CORS.
The 'https://pericope.app' is my custom domain for my Firebase project.
It looks like all other answers recommend origin:true or *.
I'm hesitant to allow all origins since it would allow anyone else access to the api. That's fine if you are creating a public service, but if you're doing anything with your data it is risky since it is a privileged environment. For example, this admin SDK bypasses any security rules you have setup for Firestore or Storage.
//Express
const express = require('express');
const app = express();
const cors = require('cors');
app.use(cors({
origin: 'https://pericope.app'
}));

Categories

Resources