Can't make serverside axios api call behind a firewall - node.js

I'm looking into axios to use for some node.js http calls to APIs while inside a corp firewall - and i'm falling down at the first hurdle.
I found an example that uses axios to do a server http call below
const axios = require('axios');
const API = 'https://jsonplaceholder.typicode.com';
/* GET api listing. */
router.get('/', (req, res) => {
res.send('api works');
});
// Get all posts
router.get('/posts', (req, res) => {
// Get posts from the mock api
axios.get(`${API}/posts`, { proxy: { host: 'http://proxy.com', port: 8080}})
//axios.get(`${API}/posts`)
.then(posts => {
res.status(200).json(posts.data);
})
.catch(error => {
res.status(500).send(error)
});
});
module.exports = router;
but when i'm behind the firewall i get an error below
// http://localhost:3000/api/posts
{
"code": "ENOTFOUND",
"errno": "ENOTFOUND",
"syscall": "getaddrinfo",
"hostname": "http://proxy.com",
"host": "http://proxy.com",
"port": 8080,
"config": {
"transformRequest": {
},
"transformResponse": {
},
"timeout": 0,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1,
"headers": {
"Accept": "application/json, text/plain, */*",
"User-Agent": "axios/0.15.3",
"host": "jsonplaceholder.typicode.com"
},
"method": "get",
"proxy": {
"host": "http://proxy.com",
"port": 8080
},
"url": "https://jsonplaceholder.typicode.com/posts"
it works find when i switch to a direct connection to the internet and the proxy setting are what i use for npm - i'm not sure if the final solution will be inside or outside of the firewall but i can't figure out to do this either specific to this api or even globally just for dev.. any help would be appreciated..

I believe that axios just wants the host in the proxy config, not the URL with protocol:
"proxy": {
"host": "proxy.com",
"port": 8080
}

Related

NestJS cors error when do request from client on Next.js

Deploy my api project on vercel, but have cors error, when I do http request from a client on Next.js.
My Nest configuration is like in docs.
const app = await NestFactory.create(AppModule, { cors: true });
But I also tried diferent configurations
app.enableCors({
origin: ['http://localhost:3000', 'https://api-filmgen-pearl.vercel.app'],
methods: ['GET', 'POST'],
credentials: true,
});
//or
app.enableCors();
//or
app.enableCors({
credentials: true,
origin: [/localhost:\d+$/, /\.vercel\.app$/, /\.herokuapp\.com$/],
allowedHeaders: 'origin, content-type, accept, application/json',
});
In Postmar, Swagger or local everything is ok.
UPD: My nest config
/** #type {import('next').NextConfig} */
const { i18n } = require('./next-i18next.config');
const nextConfig = {
webpack(config) {
config.module.rules.push({
test: /\.svg$/i,
issuer: /\.[jt]sx?$/,
use: ['#svgr/webpack'],
});
return config;
},
reactStrictMode: true,
compiler: {
styledComponents: true
},
i18n
}
module.exports = nextConfig
In React client app requests are also falling
Since Heroku is a separate domain than Vercel which is also https, use the secure: true and sameSite: 'none' flags in your CORS config.
Next.js mentions in their Caveats section that requests are by-default same-origin. They also provide a guide on how to customize route CORS behavior in the CORS Request Helpers guide.
Add options to vercel config
{
"version": 2,
"builds": [
{
"src": "src/main.ts",
"use": "#vercel/node"
}
],
"routes": [
{
"src": "/(.*)",
"dest": "src/main.ts",
"methods": ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"]
}
]
}

Problem with CORS in Nest.js app after deployment on Vercel

POST request in my Nest.js app not working after deployment on Vercel and I receive CORS error, but cors in my app is enable and when I send GET request all working. When I test my request in postman all working. I am not sure but maybe this error can happen through that I use React Query or problem with vercel and I not right deployment my app.
I receive such error:
Access to XMLHttpRequest at 'https://server-store.vercel.app/api/auth/login' from origin 'https://next-store-liard-three.vercel.app' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
And I enabled CORS such method:
app.enableCors({
origin: ['http://localhost:3000', 'https://next-store-liard-three.vercel.app'],
allowedHeaders: ['Accept', 'Content-Type'],
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS',
preflightContinue: false,
optionsSuccessStatus: 204,
credentials: true,
});
This is my file vercel.json:
{
"version": 2,
"name": "next-store-server",
"buildCommand": "npm start",
"installCommand": "npm install",
"builds": [
{
"src": "dist/main.js",
"use": "#vercel/node"
}
],
"routes": [
{
"src": "/(.*)",
"dest": "dist/main.js",
"methods": ["GET", "POST", "PATCH", "PUT", "DELETE"]
}
]
}
Also I try enable CORS other way, but it is not help me.
I try enable CORS, such method:
const app = await NestFactory.create(AppModule, { cors: true });
On client I using Next.js, reactQuery and axios for sending request
import axios from "axios";
import { FAuth, IUser } from "./Auth.types";
const AuthService = {
async registration(dto: IUser) {
const { data } = await axios.post<FAuth>(
`${process.env.NEXT_PUBLIC_SERVER_API_URL}/api/auth/registration`,
dto,
);
return data;
},
async login(dto: IUser) {
const { data } = await axios.post<FAuth>(`${process.env.NEXT_PUBLIC_SERVER_API_URL}/api/auth/login`, dto);
return data;
},
};
This my custom useMutation hooks
export const useRegistration = () =>
useMutation((dto: Omit<IUser, "_id">) => AuthService.registration(dto), {
onSuccess: () => {
toast.success("Success", {
theme: "colored",
});
},
onError: (data: any) => {
toast.error(data.response.data.message, {
theme: "colored",
});
},
});
export const useLogin = () =>
useMutation((dto: Omit<IUser, "_id">) => AuthService.login(dto), {
onSuccess: () => {
toast.success("Success", {
theme: "colored",
});
},
onError: (data: any) => {
toast.error(data.response.data.message, {
theme: "colored",
});
},
});
Try to add "OPTIONS" into methods, this worked for me
vercel.json:
{
"version": 2,
"builds": [{ "src": "src/main.ts", "use": "#vercel/node" }],
"routes": [
{
"src": "/(.*)",
"dest": "src/main.ts",
"methods": ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"]
}
]
}

Strapi api not giving a response when registering user even though it was updated in the admin panel

I am using Strapi with postgres to register a new Strapi end user and I am using the following code to send a post request with the new user's credentials:
//...
try {
// encrypt the user password
const encryptedUserPassword = await bcrypt.hash(password, 10);
const response = await axios.post(
"http://localhost:1337/api/auth/local/register",
{
username,
email: email.toLowerCase(),
password: encryptedUserPassword,
}
);
} catch (err) {
console.log(err);
res.status(500).send({ message: ["Registration failed"], error: err });
}
// ...
The problem that I am facing is that whenever I send the post request, the data is being successfully updated in the Strapi admin panel and eventually in the postgres database but it is not returning a successful response and it continues to process until it throws an Axios error even though the data is updated in my Strapi admin panel.
This is the error that I received when I send the post request to register a new user:
{
"message": [
"Registration failed"
],
"error": {
"message": "Request failed with status code 400",
"name": "AxiosError",
"config": {
"transitional": {
"silentJSONParsing": true,
"forcedJSONParsing": true,
"clarifyTimeoutError": false
},
"transformRequest": [
null
],
"transformResponse": [
null
],
"timeout": 0,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1,
"maxBodyLength": -1,
"env": {},
"headers": {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/json",
"User-Agent": "axios/0.27.2",
"Content-Length": 130
},
"method": "post",
"url": "http://localhost:1337/api/auth/local/register",
"data": "{\"username\":\"testuser04\",\"email\":\"testuser09#email.com\",\"password\":\"$2a$10$pqeADn.WL4BqHYpTonVl2.KYqoxtuJZyvdpgc659W90zmsu4Wo2jW\"}"
},
"code": "ERR_BAD_REQUEST",
"status": 400
}
}
I am using the recommended Strapi node version 14.19.3 with the following package.json dependencies:
"devDependencies": {},
"dependencies": {
"#strapi/strapi": "4.2.3",
"#strapi/plugin-users-permissions": "4.2.3",
"#strapi/plugin-i18n": "4.2.3",
"pg": "8.6.0"
},
Could someone please help me or give me some tips on what I am doing wrong? Thank you in advance
Well, I just resolved this problem. It turns out that just needed to set the default value for the email confirmation in the admin panel to false. Also, I needed to authorize my application to make requests directly to the API

Laravel Echo with NodeJS HTTPS doesn't work

I've been developing this NodeJS application that takes advantage of Laravel Echo's functionalities to receive information from a server through socket connection.
Server-side
Laravel Echo Server with Laravel 5.7.19
Client-side
"laravel-echo": "^1.5.2"
"socket.io": "^2.2.0"
import Echo from '../../node_modules/laravel-echo/dist/echo.common.js'
import Socketio from 'socket.io-client';
let echo = new Echo({
broadcaster: 'socket.io',
host: 'https://smartfish.danymota.com:8080/',
encrypted: true,
secure: true,
client: Socketio,
auth: {
headers: {
'Authorization': 'Bearer ' + this.token.bearerToken,
},
},
});
echo.private('central.' + macAddress)
.listen('RulesUpdated', (response) => {
handleRules(JSON.parse(response.aquarios))
console.log(new Date().toLocaleString() + " - Rules updated")
})
Problem
Everything works fine in Http, when I switch to HTTPS it just stops working. Also, the socket connection doesn't reach the server (or at least Laravel-echo-server doesn't log it)
IMPORTANT - What I've tried
Ran the application through Browserify, and then on the browser (it works just fine on a browser, even with HTTPS)
Played around with different ports (Again, it works with HTTP, so ports are likely not the problem)
Changed the URL to wss://, /socket.io
Forced socket.io to include a secure: true on options
Changed the version of Laravel Echo
Tried importing both echo.common.js and echo.js
Notes
/api/broadcasting/auth - This is working, so problem is likely not here
Laravel echo server configuration
{
"authHost": "https://smartfish.danymota.com",
"authEndpoint": "/api/broadcasting/auth",
"clients": [{
"appId": "f7506b5e7118092c",
"key": "9015d93999f3a2f7f95a054a76fbcbfd"
}],
"database": "redis",
"databaseConfig": {
"redis": {},
"sqlite": {
"databasePath1": "/database/laravel-echo-server.sqlite"
}
},
"devMode": true,
"host": null,
"port": "8080",
"protocol": "https",
"socketio": {},
"sslCertPath": "/home/danymota/ssl/cert/smartfish.danymota.com.crt",
"sslKeyPath": "/home/danymota/ssl/private/smartfish.danymota.com.key",
"sslCertChainPath": "",
"sslPassphrase": "",
"subscribers": {
"http": true,
"redis": true
},
"apiOriginAllow": {
"allowCors": true,
"allowOrigin": "http://smartfishweb.test/api",
"allowMethods": "GET, POST",
"allowHeaders": "Origin, Content-Type, X-Auth-Token, X-Requested-With, Accept, Authorization, X-CSRF-TOKEN, X-Socket-Id"
}
}
Socket.io debug
socket.io-client:url parse https://smartfish.danymota.com:8080/socket.io +0ms
socket.io-client new io instance for https://smartfish.danymota.com:8080/socket.io +0ms
socket.io-client:manager readyState closed +0ms
socket.io-client:manager opening https://smartfish.danymota.com:8080/socket.io +0ms
socket.io-client:manager connect attempt will timeout after 20000 +4ms
socket.io-client:manager readyState opening +1ms
socket.io-client:manager connect_error +60ms
socket.io-client:manager cleanup +0ms
Thank you all in advance.
that because you have to set laravel echo server settings
use this command laravel-echo-server init and choose https when setting the protocol
or open laravel-echo-server.json
and change protocol to https
{
"authHost": "https://smartfish.danymota.com:8080",
"authEndpoint": "/broadcasting/auth",
"clients": [
{
"appId": "It generates it from the command init",
"key": "It generates it from the command init"
}
],
"database": "Your database driver",
"databaseConfig": {
"redis": {},
"sqlite": {
"databasePath": "/database/laravel-echo-server.sqlite"
}
},
"devMode": true,
"host": null,
"port": "6001", // your node js port the default is 6001
"protocol": "https", // change it here
"socketio": {},
"sslCertPath": "",
"sslKeyPath": "",
"sslCertChainPath": "",
"sslPassphrase": "",
"apiOriginAllow": {
"allowCors": true,
"allowOrigin": "Your domain with the port",
"allowMethods": "GET, POST",
"allowHeaders": "Origin, Content-Type, X-Auth-Token, X-Requested-With, Accept, Authorization, X-CSRF-TOKEN, X-Socket-Id"
}
}
I've solved this problem by adding a flag rejectUnauthorized: false to laravel echo.
this.echo = new Echo({
broadcaster: 'socket.io',
host: config.ECHO_SERVER,
client: Socketio,
rejectUnauthorized: false,
auth: {
headers: {
'Authorization': 'Bearer ' + this.token.bearerToken,
},
},
})

Laravel Echo Server can not be authenticated, got HTTP status 500

I've installed both Laravel echo server and Laravel echo client.
Following is the laravel-echo-server.json configuration.
{
"authHost": "http://taxation.com",
"authEndpoint": "/broadcasting/auth",
"clients": [
{
"appId": "APP_ID",
"key": "someKey"
}
],
"database": "redis",
"databaseConfig": {
"redis": {},
"sqlite": {
"databasePath": "/database/laravel-echo-server.sqlite"
}
},
"devMode": true,
"host": "127.0.0.1",
"port": "3000",
"protocol": "http",
"socketio": {},
"sslCertPath": "",
"sslKeyPath": "",
"sslCertChainPath": "",
"sslPassphrase": ""
}
The following script listens for channel events. It builds fine with npm run dev.
import Echo from 'laravel-echo'
let token = document.head.querySelector('meta[name="token"]');
if (token) {
window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}
window.Echo = new Echo({
broadcaster: 'socket.io',
host: '127.0.0.1:3000',
reconnectionAttempts: 5
});
window.Echo.join('checked-in-1')
.listen('.user.checked_in', (e) => {
console.log(e);
});
When trying to listen for any event on start laravel-echo-server command. It keeps throwing Client can not be authenticated, got HTTP status 500.
Note :
I really didn't find anything helpful on laravel-echo-serve nor on google.
Any help will be appreciated a lot.
Laravel V5.4
Thanks
Just getting the issue because of CSRF token. Didn't passed the token to the echo.
window.Echo = new Echo({
broadcaster: 'socket.io',
host: '127.0.0.1:3000',
reconnectionAttempts: 5,
csrfToken: token.content <--
});

Resources