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!!');
});
Related
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 }
},
}
I am learning and applying authentication for my blog website!
I am using express-session to handle logins. Cookie on the browser & server sessions works fine.
However, I am having trouble retrieving cookies on the server-side express app. I tried the following:
With cookie-parser, req.cookies & req.signedCookies both returns [Object: null prototype].
Setting CORS
req.cookie & req.header.cookie returns undefined
I can see a "Cookie" header from my connection in the browser network tab.
My code / settings are as follows:
function auth (req, res, next) {
// Problem: Cannot read browser cookie of HTTP requests.
console.log('Based on browser', req.cookie, req.cookies, req.signedCookies);
next();
}
router.get('/', auth, async (req, res) => { // ... }
Middlewares
app.use(cors({
origin: ['http://localhost:3000'],
credentials: true
}));
app.use(cookieParser()) // Also tried with secret option.
app.use(session({
secret: 'top-secret',
resave: true,
rolling: true,
saveUninitialized: false,
store: store, // this is working
cookie: {
maxAge: 1000 * 60 * 60 * 24 * 14,
httpOnly: true,
secure: process.env.NODE_ENV !== 'Development',
sameSite: process.env.NODE_ENV === 'Development' ? 'lax' : 'none'
}
}))
Thank you in advance :)
Edit 1: My fetch code:
If your using http only you should consider 2 things:
Step1 while request in client side:
you should send request like this:
const req = await fetch("http://localhost:7000/api/auth/login", {
method: "POST",
credentials: "include",
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Credentials": true,
},
body: JSON.stringify({
email: formData.get("email"),
password: formData.get("password"),
}),
});
const data = await req.json();
step 2 in express:
const allowedOrigins = ["http://localhost:8000"];
const corsOptions = {
origin: function (origin, callback) {
if (allowedOrigins.indexOf(origin) !== -1) {
callback(null, true);
} else {
var msg =
"The CORS policy for this site does not " +
"allow access from the specified Origin.";
callback(new Error(msg), false);
}
},
optionsSuccessStatus: 200,
credentials: true,
};
app.use(cors(corsOptions));
now you can get coockies in express by using req.cookies.nameOfCookiesWhichYouSendThroughCoockieParser
I'm using axios (React) + Express-js on Node-js
In order to get the cookie from the server:
Simply set withCredentials: true in the axios request, you can use this config example:
const config = {
headers: {
"Content-Type": "application/json",
},
withCredentials: true,
};
In order to get this cookie from the client:
You also need to set withCredentials: true in the axios request,
And you need to install cookie-parser library on the server:
npm i cookie-parser
Import this library:
const cookieParser = require("cookie-parser");
And use the cookieParser middleware:
app.use(cookieParser());
And finally, req.cookies should return the list of your cookies.
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');
}
}
}
}
};
I'm having trouble proxies websocket using http-proxy-middleware. The error I got was Websocket connection to https://api.dsm-staging.test.site failed.
Here's the code I'm using in express :
const { createProxyMiddleware } = require("http-proxy-middleware");
const options = {
target: "https://api.dsm-staging.test.site",
changeOrigin: true,
ws: true,
};
const proxy = createProxyMiddleware(options);
app.use("/v1/*", proxy);
This is my code in front end :
this.socket = io("https://api.dsm-staging.app.test.site", {
reconnectionAttempts: 5,
reconnectionDelayMax: 10000,
extraHeaders: {
Authorization: `Bearer ${token}`,
},
transports: ["websocket"],
});
this.socket.on("connect", () => {
console.log(this.socket.connected);
});
I've got problem with proxy in react app.
Target: I've got two react apps, first app is on localhost:3000 and second on localhost:3001. What I want? => When in first app I'll click on:
<a href="/app2">
<button>Second App Open</button>
</a>
Then url will change from localhost:3000 into localhost:3000/app2 and second react app show what has got in url localhost:3001.
I imported http-proxy-middleware library and create in src direction file setupProxy.js and inside:
const {createProxyMiddleware} = require("http-proxy-middleware");
module.exports = function(app) {
app.use(
createProxyMiddleware('/app2',{
target: 'http://localhost:3001',
changeOrigin: true,
prependPath: false,
secure: false,
logLevel: 'debug',
ws:true
})
);
app.listen(3000)
};
Anyone could help me with this?
Also I tried this code in setupProxy.js:
const express = require('express')
const {createProxyMiddleware} = require("http-proxy-middleware");
app = express()
app.use(
createProxyMiddleware('/app2',{
target: 'http://localhost:3001',
changeOrigin: true,
prependPath: false,
secure: false,
logLevel: 'debug',
ws:true
})
);
app.listen(3000)
But then I've received error that require(...) is not a function oraz that express is not a function, when I take express into {} then also occurs error.
I know it's late and I came across the same issue. Keeping what worked for me so that others can give it a try.This code is tested for react app created with create-react-app.
I proxied this endpoint - https://services.odata.org/V2/Northwind/Northwind.svc/Customers?$format=json
setupProxy.js
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = (app) => {
app.use(createProxyMiddleware('/api2', {
target: 'https://services.odata.org/V2/Northwind/Northwind.svc/',
changeOrigin: true,
pathRewrite: { '^/api2': '' }
})
);
}
Your .js file
triggerCORSCall() {
axios.get(`/api2/Customers?$format=json`)
.then(response => {
alert('Success');
}).catch(error => {
alert('Failure');
console.log(error);
})
}