I am trying to connect to my API, hosted on a remote VPS, via Postman but can't seem to find any definitive guides on how to do it.
The VPS has a frontend app (Vue) that connects to Express using Nginx reverse proxy. That works fine.
However, I want to share some of the Express API with another client not hosted on the same server. For example, connecting from Postman with user authentication to just share data in JSON format.
If anyone can give me any advice on how to achieve this I would much appreciate it.
EDIT
Here is an example request I am trying from Postman. Express is confirmed running on 3001 on the VPS.
http://vps-url:3001/test
This is the corresponding route in Express
app.get("/test", (req,res)=>{
res.json({ msg: 'Hello from VPS!' })
})
When I try to access in Postman, is just hangs.
I have also this CORS config to allow connection from my local machine using my public IP.
app.use((req, res, next) => {
const corsWhitelist = [
'http://vps-url.com',
'https://anotherclient',
'70.80.xxx.xxx' // my machine IP
];
if (corsWhitelist.indexOf(req.headers.origin) !== -1) {
res.header('Access-Control-Allow-Origin', req.headers.origin);
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
}
next();
});
Related
when I run the following code from the client side in javascript as the coinbase cloud documentation says https://docs.cloud.coinbase.com/exchange/reference/exchangerestapi_getcoinbaseaccounts
const options = {
method: 'GET',
headers: {
Accept: 'application/json',
'cb-access-key': 'Apikey',
'cb-access-passphrase': 'Mypassphrase',
'cb-access-sign': cb_access_sign,
'cb-access-timestamp': cb_access_timestamp
}
};
fetch('https://api.exchange.coinbase.com/coinbase-accounts', options)
.then(response => response.json())
.then(response => console.log(response))
.catch(err => console.error(err));
when I do it with axios the same thing happens
the following error appears in console: "Access to fetch at 'https://api.exchange.coinbase.com/coinbase-accounts' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field cb-access-passphrase is not allowed by Access-Control-Allow-Headers in preflight response."
what am I doing wrong?
You can't do this in the browser, you need to do it from the web server. You can either display the data when the page loads or use vue/react and write your own interaction with the webserver.
edit: doing this in the browser makes your keys visible...
Coinbase API has misconfigured CORS (or intentionally require you to make API calls from a server). Regardless, this makes it very hard to test in a dev environment. This can be solved using a proxy. This can be configured using cors-anywhere which changes the api call flow from:
Client (localhost:3000) <-> Coinbase API (api.exchange.coinbase.com)
to
Client (localhost:3000) <-> Proxy Server (www.your-proxy-server.com) <-> Coinbase API (api.exchange.coinbase.com)
In summary, coinbase will only see a request coming from your proxy server and does not care/know where the proxy server sends back the data. Cors-anywhere will also include the headers and data along with the request.
Do not use public cor-anywhere servers unless you are quickly testing something. It is best to set up your own.
Using Firebase
I used cors-server to set mine up using firebase functions. You want your Firebase functions to look like the following:
const {onRequest} = require("firebase-functions/v2/https");
const corsAnywhere = require('cors-anywhere');
const cors = require("cors")({origin:true})
const corsServer = corsAnywhere.createServer({
originWhitelist: [
'http://localhost:3000',
],
requireHeader: ['origin', 'x-requested-with'],
removeHeaders: ['cookie', 'cookie2'],
});
exports.proxy = onRequest((request, response) => {
cors(request,response,() =>{
corsServer.emit('request', request, response);
})
});
and an example of a request in your client code
return(
axios({
url: `https://proxy-your-function-id.a.run.app/https://api.exchange.coinbase.com/profiles`,
headers: await getHeaders(options),
method: 'GET',
data: options.body
}).then((response)=>{
return(response)
}).catch((err)=>{
return(err.response)
})
)
Edit: It should also be noted that Coinbase is getting rid of Coinbase Pro and its API end of 2022. Coinbase exchange and its API will still be available at https://api.exchange.coinbase.com however Pro users will be merged into Advanced Trading on their main platform which uses oAuth to link the API (or standard keys for personal projects).
This question has been asked a million times, but I've tried it all and nothing seems to work.
My situation:
I've deployed a node/express backend as a Google Cloud Run service.
I am running my frontend locally, trying to login to my backend in the cloud. Frontend is served on http, backend on https. I have enabled cors on the backend. My config is:
app.use(cors({
origin: 'http://localhost:3000',
credentials: true,
}));
I am using axios, and I have set withCredentials: true:
axios.defaults.baseURL = ApiURL;
const { data } = await axios({
method: 'post',
url: `/api/login`,
data: {
username: this.state.username,
password: this.state.password,
keepLoggedIn: this.state.keepLoggedIn,
},
withCredentials: true,
});
This setup works perfectly when I run my backend locally, but of course there is no cors then. When I try to log in when the frontend is pointed at the Cloud Run service, I get a response from the backend with a set-cookie header as expected, but no cookie ever appears in the Storage > Cookies section of the Chrome dev console as it does with my local backend. There is then of course nothing sent with the rest of my axios requests, which need the cookie.
I've been at this for a full day and its driving me nuts. I'm sure there is something simple I'm missing. Any ideas?
I have a user authentication server setup using Express and Node.js in my localhost Port 3333 and I am trying to connect to the endpoint in Next.js port 3000 using isomorphic-unfetch for the fetch. I am getting a CORS 401 error, I have done a fair bit of research already but just wanted to know whether it was possible connecting to a Express server on localhosts? I have tried adding "Access-Control-Allow-Origin": "*", "Content-Type": "multipart/form-data" to a header object. The express server has cors setup already.
This function below is called on click of a button.
onLoginClick = async () => {
let header = new Headers({
"Access-Control-Allow-Origin": "*",
"Content-Type": "multipart/form-data"
});
const res = await fetch("http://localhost:3333", {
method: "POST",
header,
body: JSON.stringify({
username: "USER",
password: "PASSWORD"
})
});
}
Error message -
http://localhost:3333/ 401 (Unauthorized)
Response {type: "cors", url: "http://localhost:3333/", redirected: false, status: 401, ok: false, …}
First of all, CORS is configured on the server side. You configure your server to allow calls from specific origins.
In your code, onLoginClick is a client-side code, it runs on the browser, client cannot decide which origin the server should allowed to, that would defeat the purpose of having CORS.
Usually you don't need to change the cors configuration in a Next.js app, because you would be calling the API from the same origin that hosted the client side app.
By default, Next.js only support same-origin for API Routes, if you need to customize it, you can use micro-cors.
So i have a react app which if someone is logged in will check for it's account level and based on that will enable or disable features. It worked until it was all localhost, but now i have a server in the cloud and the request is pending forever. Other requests to the same endpoint works fine. I tried changing the address to localhost, but then it looks for the API server on my PC. It's strange because the same endpoint works with other requests. This single request also works on localhost but not if i use server's IP. Here's an image of the Network page of Chrome development tools: https://i.ibb.co/c2r8Js1/Screenshot-at-2019-12-27-15-11-41.png
getLoggedLevel = () => {
var URL = process.env.REACT_APP_API_URL;
var URL2 = 'http://localhost:8000/requests'
axios({
url: URL,
method: 'post',
data: {
message: 'getLoggedLevel',
username: JSON.parse(localStorage.getItem('loggedUser')).username
}
}).then(res => {
this.setState({loggedLevel: res.data.level})
})
}
Edit: I created a separate endpoint for that single request, and it's 404 however in firefox it's 200 for OPTIONS... Now i'm really confused :(
I have two express-based servers...
Server 1: API runs on port 3010
Server 2: UI runs on port 3000
On server 1 in the app.js file (autogen) I have the following...
// Allow requests from the ui
app.use(function (req, res, next) {
// TODO: Make specific
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
});
But when I try to POST to that address from a Server 2 page I get the following in the Chrome Console....
Failed to load http://localhost:3010/search: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.
I also tried res.header('Access-Control-Allow-Origin', 'http://localhost:3000'); and others but none seem to work
What am I missing?
I moved the app.use ahead of the other generated app.uses and it seems to work. Still not sure why, guessing a middleware item in the autogen isn't calling next properly.