Strapi session not found on Chrome - javascript

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

Related

Cookie is not included in request header / Server side cannot read req.cookies

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.

How to fix CORS policy issue with get request?

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

How to proxy a websocket properly?

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

Why does webpack proxy do not work (Access-Control-Allow-Origin error)?

So, I am trying to bypass CORS on the server by proxying my requests. I am using webpack and axios.
So, here is webpack dev server options:
devServer: {
contentBase: './build/',
historyApiFallback: true,
hot: true,
quiet: true,
open: false,
port,
noInfo: false,
clientLogLevel: 'error',
proxy: {
'/api/**': {
target: 'http://mydev.com',
changeOrigin: true,
secure: false
}
}
}
and axios:
const axiosInstance = axios.create({
baseURL: 'http://mydev.com',
timeout: 30000,
headers: {
'Content-Type': 'application/json',
'X-AUTH-TOKEN':
'my-token
},
data: {}
});
But still my origin is localhost and option request does not go through. Hence I am have this error.
Just to clarify: I want to make request from localhost to mydev.com with JSON content and bypass CORS settings.
Thanks!
Webpack's proxy option actually creates a small reverse proxy server, which connects to your target endpoint.
In this case, your app (axios instance) should connect to your proxy:
const axiosInstance = axios.create({
baseURL: 'localhost:3000/api' // your local server here
...
});

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!!');
});

Categories