How to fix CORS policy issue with get request? - javascript

please help me to solve CORS policy issue, it happens when I'm trying to make a get request to applications endpoint, and issue is only reproducible from http://localhost:8080/ on prod request works fine.
vue.config.js file
module.exports = {
devServer: {
proxy: 'https://spinstatus.zenoss.io/'
}
}
request method
const grabApps = async () => {
const res = await axios({
method: 'get',
url: `${spinnakerURL}/gate/applications`,
withCredentials: false,
crossdomain: true,
headers: {
'Access-Control-Allow-Origin': '*',
}
});
return res.data || []
}
error
headers from localhost request
headers from prod request

Change the devServer configuration in vue.config.js like this:
module.exports = {
devServer:
{
proxy:
{
'/gate':
{
target: 'https://spinstatus.zenoss.io',
changeOrigin: true,
onProxyReq: (proxyReq, req, res, options) =>
{
proxyReq.setHeader('Origin', 'https://spinstatus.zenoss.io');
}
}
}
}
};

Related

CORS origin always undefined when fetching data

Using this server configuration
import Cors from 'cors';
const cors = Cors({
methods: ['GET', 'POST', 'HEAD'],
allowedHeaders: 'X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version, X-Api-Authorize, X-Authorize',
credentials: true,
origin: (origin, callback) => {
console.log("*** TESTING", origin);
return callback(null, true); // debug, otherwise nothing works
},
optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
});
const applyCors = async (req, res) => new Promise((resolve, reject) => {
cors(req, res, (result) => {
if (result instanceof Error) {
reject(result);
} else {
resolve(result);
}
});
});
export const apiMiddleware = handler => async (req, res) => {
await applyCors(req, res);
// ... req is extended with utils
return handler(req, res);
};
And a client fetch request like
const response = await fetch(`/api/data`, {
credentials: 'same-origin', // also tried "include"
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-Api-Authorize': 'secret'
},
method: 'GET'
});
The server console.log always prints
*** TESTING undefined
When inspecting the request, I see the X-Api-Authorize header, but not Origin. What's missing?
fetch(`/api/data`
That's a relative URL, so you are making a same-origin request.
The origin header is only included in cross-origin requests.
(That's a simplification, as jub0bs points out, there are other times it will be included, but your code doesn't meet any of those conditions).

Strapi session not found on Chrome

I built a website with Nuxt and Strapi. I added a cart system using the ctx.session. It works well on local, but when in prod, the session can't be retrived when using Chrome or Safari. But it's perdect with Firefox.
I logged to see what's happening and it seems that the sessions is never stored. After an action is done, nothing remains.
Here is my middleware.js :
const isProd = process.env.NODE_ENV === 'production'
module.exports = {
//...
settings: {
cors: {
enabled: true,
// headers: '*',
credentials: true,
origin: isProd
? ['https://xxxxxx.com', 'https://yyyyy.xxxxxx.com']
: ['http://localhost:3000', 'http://localhost:1337']
},
logger: {
level: 'trace'
}
},
}
and my server.js :
module.exports = ({ env }) => ({
host: env('HOST', '0.0.0.0'),
port: env.int('PORT', 1337),
admin: {
auth: {
secret: env('ADMIN_JWT_SECRET', 'XXXXXXXXXXXX'),
},
},
cron: { enabled: true }
});
On the front side, here is my Axios config :
const apiClient = axios.create({
baseURL: `${process.env.baseUrl}/`,
withCredentials: true,
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
timeout: 10000,
})
Thank you
I finally found the solution!
I was missing the session activation in the middleware.js config file.
module.exports = {
//...
settings: {
...otherSettings,
session: { enabled: true }
},
}

Proxying an endpoint to avoid CORS issues

I am using an external api that doesn't allow client side POST request. I can make a POST request using node.js and I am getting my desired response on the server. I am stuck trying to figure out how to get the response from the server into my HTML file.
const https = require("https");
const data = JSON.stringify({
key: "value"
});
const options = {
hostname: "url",
port: 443,
path: "/path",
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": data.length
}
};
const req = https.request(options, res => {
console.log(
`statusCode: ${res.statusCode} statusMessage: ${res.statusMessage}`
);
res.setEncoding("utf8");
res.on("data", chunk => {
console.log(chunk);
});
});
req.on("error", error => {
console.error(error);
});
req.write(data)
req.end();
This is my server.js file, I'm not sure what the next step is to get in a file.

ReactJS get external Json

I want to make a component with Reactjs to get json from an url, I tried with (Axios, Fetch, Jsonp...) and other package.
With Axios and Jsonp I had CORS errors, impossible to fix the issue.
With Fetch I can disable the cors with 'mode': 'no-cors' but no data are collected.
Here is my code :
getData() {
const header = {
'Access-Control-Allow-Origin': '*',
'mode': 'no-cors'
};
this.serverRequest = fetch('https://www.cryptopia.co.nz/Exchange/GetTradePairChart?tradePairId=5355&dataRange=2&dataGroup=60', header)
.then(response => response.json())
.then(json => {
console.log(json);
this.setState({
altcoinsData: json
});
}).catch(e => {
console.log(e);
});
}
Error :
SyntaxError: Unexpected end of input
at App.js:30
at
If you are using webpack-dev-server, add proxy service in webpack.config.js to avoid CROS.
devServer: {
port: 8080,
stats: 'errors-only',
proxy: {
'/api': {
target: 'http://localhost:20404', //http://localhost:20403/',
secure: false
}
}
}
If not you can start a express server with http-proxy-middleware to proxy the ajax request to the required end point. Please find a sample server.js which includes express and webpack config.
Hope it helps :)
var webpack = require('webpack');
var Agent = require('agentkeepalive');
var config = require('./webpack.config.js');
var https = require('https');
var proxy = require('http-proxy-middleware');
const express = require('express');
const path = require("path");
const webpackDevMiddleware = require('webpack-dev-middleware');
var app = express();
var compiler = webpack(config);
app.use(
'/api',
proxy({
target: 'http://10.134.116.186:1521/',
changeOrigin: true,
agent: new Agent({
maxSockets: 100,
keepAlive: true,
maxFreeSockets: 10,
keepAliveMsecs: 100000,
timeout: 6000000,
keepAliveTimeout: 90000 // free socket keepalive for 90 seconds
})
})
);
app.use(
'/dist',
proxy({
target: 'http://localhost:8080/',
changeOrigin: true,
agent: new Agent({
maxSockets: 100,
keepAlive: true,
maxFreeSockets: 10,
keepAliveMsecs: 100000,
timeout: 6000000,
keepAliveTimeout: 90000 // free socket keepalive for 90 seconds
})
})
);
app.use(
webpackDevMiddleware(compiler, {
hot: true,
historyApiFallback: true,
contentBase: config.output.path,
publicPath: config.output.publicPath,
headers: { 'Access-Control-Allow-Origin': '*' }
})
);
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
app.listen(7071, 'localhost', function(err, result) {
if (err) {
return console.log(err);
}
console.log('Webpack Dev Server is fired up!!');
});

Setup Node.js HTTPS to work with HAPROXY

I'm trying to make my nodejs app to communicate with HAPROXY via https. The idea is that nodejs sends message to haproxy via https, haproxy routes message forward.
I used request.js library and all worked fine, but now I need to perform this task without any libraries. The scenario is following. If environment variable is 1, I should use HTTP, in other cases -HTTPS. The problem is that when I use https and haproxy, I get "Socket hangup error", but everything works fine with request.js. Here is my code.
const protocol = process.env.NODE_ENV === 1 ? require('http') : require('https');
then I configure HTTPS
this.api = url.parse(app.get('API_HAPROXY'));
this.options = {
port: this.api.port,
hostname: this.api.hostname,
path: '/api/report',
method: 'POST',
headers: {
"Content-Type": "application/json",
},
rejectUnauthorized: false,
requestCert: true,
agent: false
};
Because I don't want to use ca to validate ssh keys I use NODE_TLS_REJECT_UNAUTHORIZED=0
reportData(json) {
const req = protocol.request(this.options, (res) => {
res.on('error', (err) => {
this.logger.error(`Failed to report ${err.message}`)
})
});
req.write(JSON.stringify(json));
req.end();
req.on('error', (err) => {
this.logger.error(`Failed to report ${err.message}`);
});
}
In this case I get socket hangup error while using HTTPS
Here is my request configuration
request({
uri: `${this.api}/api/report`,
method: 'POST',
json,
}, (err, response) => {
if (err || response.statusCode !== 200) {
this.logger.error(`Failed to report : ${err ? err.message : response.statusCode}`);
} else {
this.logger.info(`Report was sent`);
}
});
The issue was fixed by adding content-length header to the options.headers.
this.api = url.parse(app.get('API_HAPROXY')); this.options = {
port: this.api.port,
hostname: this.api.hostname,
path: '/api/report',
method: 'POST',
headers: {
"Content-Type": "application/json",
"Content-Length: <calculated length of the object you want to send in bytes >
},
rejectUnauthorized: false,
requestCert: true,
agent: false
};

Categories