getServerSideProps on NextJS converting the localhost to ::1 - next.js

I have a NextJS project which has an index page:
pages/index.jsx
const Home = NextPage<Props> = (props) => {
...
...
...
}
export default async function getServerSideProps() {
posts = await('http://localhost:8000/posts/')
return {
props: { posts }
}
}
But the domain of the fetch request is being changed to the ipv6 address (::1) and this causes a connection refused error. (Backend server is not accepting ipv6 requests)
My question is why NextJS is doing this on getServerSideProps? (Fetch requests from frontend is not doing the same thing)
Here is some more info about my issue:
URL that trying to be fetched: http://localhost:8000/posts/?ishot=true
Options on that fetch request:
{
mode: 'cors',
cache: 'no-cache',
credentials: 'include',
headers: {},
redirect: 'follow',
method: 'GET'
}
The error that I am receiving:
error - TypeError: fetch failed
at Object.fetch (node:internal/deps/undici/undici:14152:11)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
cause: Error: connect ECONNREFUSED ::1:8000
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1494:16) {
errno: -61,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '::1',
port: 8000
},
page: '/'
}

Related

Failed to fetch. Possible Reasons: Cors Network failure URL Scheme

I trying to do a swagger documentation for an Express API and Firebase database, when I make request to my database in local with postman it work, but with the swagger interface I get this error:
Failed to fetch.
Possible Reasons:
CORS
Network Failure
URL scheme must be "http" or "https" for CORS request.
For my documentation I use swagger-autogen and swagger-ui-express
there is a example for the login endpoint:
const app = express();
const port = process.env.PORT || 8080;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(
cors({
origin: `http://localhost:${port}`,
methods: ["GET", "POST", "DELETE", "PUT", "PATCH"],
credentials: true,
})
);
app.use(helmet());
app.use(morgan("combined"));
app.get("/", (req, res) => {
res.status(200).json({ message: "Welcome" });
});
app.use("/api-docs", swaggerUi.serve, swaggerUi.setup(swaggerFile, options));
swagger.js
const outputFile = "schemas/swagger.json";
const endpoints = \["routes/auth.js", "routes/menus.js"\];
const doc = {
info: {
version: "1.0.0",
title: "Menus API documentation",
description: "Documentation of MenusAPI",
termsOfService: "http://swagger.io/terms/",
contact: {
email: "contact#toto.com",
},
license: {
name: "Apache 2.0",
url: "http://www.apache.org/licenses/LICENSE-2.0.html",
},
},
servers: \[
{
url: "https://localhost:8081/menusapi/api/v1/",
},
\],
host: "/",
consumes: \["application/json"\],
produces: \["application/json"\],
securityDefinitions: {
OAuth2: {
type: "oauth2",
flows: {
authorizationCode: {
authorizationUrl: process.env.AUTH_UTI,
tokenUrl: process.env.TOKEN_URI,
scopes: {
read: "Grants read access",
write: "Grants write access",
},
},
},
},
bearerAuth: {
type: "http",
scheme: "bearer",
bearerFormat: "JWT",
},
},
"#definitions": {
AddUser: userSchema.registration,
Login: userSchema.login,
Menus: menusSchema,
},
};
swaggerAutogen(outputFile, endpoints, doc).then(() =\> {
require("../app");
});
routes/auth.js
router.post("/login", auth.login);
controllers/auth_controller.js
exports.login = async (req, res) =\> {
/\* #swagger.tags = \['Auth'\]
\#swagger.description = 'Service to login';
\#swagger.summary = "Service to login a user to the app";
\#swagger.security = \[{
"OAuth2": \[
'read',
'write'
\]
}\]
\#swagger.responses\[200\] = {
description: 'Login sucess',
schema: {
"message": "Successfully connected!",
"jwt": "A very long token",
"refresh_jwt": "An other long token"
}
}
console error:
throw new Error(`${(0, validate_1.invalidArgumentMessage)(arg, desc)} Cannot use "undefined" as a Firestore value${fieldPathMessage}. ` +
^
Error: Value for argument "value" is not a valid query constraint. Cannot use "undefined" as a Firestore value
I looked everywhere but I really don't know what to do

Strapi athentication returns AxiosError: Request failed with status code 400

using Strapi with Next js. Trying to authenticate with following code
const authenticate = () => {
const paylaod = {data: {
identifier: email,
password: password
}}
console.log(paylaod)
axios.post(`http://localhost:1337/api/auth/local`, paylaod).then((res, err) => {
console.log(res, err)
console.log(res,err)
const { jwt, user } = res.data
window.localStorage.setItem('jwt', jwt)
window.localStorage.setItem('userData', JSON.stringify(user))
router.push({
pathname: '/calendar',
});
}).catch(err => {
console.log(err)
})
}
Response I'm getting is:
AxiosError {message: 'Request failed with status code 400', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}
Dug every possible answer in forums and Stackoverflow, but nothing helped.
User I'm using is not super admin, registered fresh one in Strapi admin.
this is how my middleware list looks like
export default [
'strapi::errors',
'strapi::security',
'strapi::cors',
'strapi::poweredBy',
'strapi::logger',
'strapi::query',
'strapi::body',
'strapi::session',
'strapi::favicon',
'strapi::public',
];
and here's my (scrappy) env
HOST='127.0.0.1'
PORT=1337
APP_KEYS="gfhgfhgfhg,hfghghgf"
API_TOKEN_SALT="adfasdfads"
ADMIN_JWT_SECRET="adfasdfasdf"
JWT_SECRET="sdasdadfasdf"

Why does fetching from 127.0.0.1 work but not from localhost within getStaticProps?

I am fetching data from my flask api that listens on port 5000 within getStaticProps. I noticed that fetching http://127.0.0.1:5000/posts works but not http://localhost:5000/posts. The same issue occurs for getServerSideProps too. But both urls work if I am fetching from client-side.
Here is my code:
import axios from "axios";
export default function SSG({ data }: { data: any }) {
return <div>SSG</div>;
}
export async function getStaticProps() {
const res = await axios.get("http://localhost:5000/posts");
return {
props: {
data: res["data"],
},
};
}
And here is the error message:
error - AxiosError: connect ECONNREFUSED ::1:5000
at AxiosError.from (webpack-internal:///./node_modules/axios/lib/core/AxiosError.js:94:14)
at RedirectableRequest.handleRequestError (webpack-internal:///./node_modules/axios/lib/adapters/http.js:550:75)
at RedirectableRequest.emit (node:events:513:28)
at eventHandlers.<computed> (/Users/tdawg/Desktop/axios-test/node_modules/follow-redirects/index.js:14:24)
at ClientRequest.emit (node:events:513:28)
at Socket.socketErrorListener (node:_http_client:481:9)
at Socket.emit (node:events:513:28)
at emitErrorNT (node:internal/streams/destroy:151:8)
at emitErrorCloseNT (node:internal/streams/destroy:116:3)
at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
port: 5000,
address: '::1',
syscall: 'connect',
code: 'ECONNREFUSED',
errno: -61
It doesn't seem like an axios issue as I am observing the same even with Next 13's fetch.
Why does 127.0.0.1 work but not localhost?
The 127.0.0.1 address specifies IPv4, and it looks like localhost is resolving to IPv6 (i.e. address: '::1').
Presumably your software environment is not setup correctly for IPv6.

What could cause a promise to fail in Nativescript angular2?

I am trying to Http GET from a database , where I do have access and can reproduce the GET result in Postman.
I have created a service in angular2 {N} where I execute this GET but I get an error of :
JS: EXCEPTION: Error: Uncaught (in promise): Response with status: 200 for URL: null
JS: STACKTRACE:
JS: Error: Uncaught (in promise): Response with status: 200 for URL: null
JS: at resolvePromise (/data/data/org.nativescript.ndemo/files/app/tns_modules/zone.js/dist/zone-node.js:496:32)
JS: at resolvePromise (/data/data/org.nativescript.ndemo/files/app/tns_modules/zone.js/dist/zone-node.js:481:18)
JS: at /data/data/org.nativescript.ndemo/files/app/tns_modules/zone.js/dist/zone-node.js:529:18
JS: at ZoneDelegate.invokeTask (/data/data/org.nativescript.ndemo/files/app/tns_modules/zone.js/dist/zone-node.js:314:38)
JS: at Object.NgZoneImpl.inner.inner.fork.onInvokeTask (/data/data/org.nativescript.ndemo/files/app/tns_modules/#angular/core/src/zone/ng_zone_impl.js:37:41)
JS: at ZoneDelegate.invokeTask (/data/data/org.nativescript.ndemo/files/app/tns_modules/zone.js/dist/zone-node.js:313:43)
JS: at Zone.runTask (/data/data/org.nativescript.ndemo/files/app/tns_modules/zone.js/dist/zone-node.js:214:48)
JS: at drainMicroTaskQueue (/data/data/org.nativescript.ndemo/files/app/tns_modules/zone.js/dist/zone-node.js:432:36)
JS: Unhandled Promise rejection: Response with status: 200 for URL: null ; Zone: angular ; Task: Promise.then ; Value: Response with status: 200 for URL: null
JS: Error: Uncaught
(in promise): Response with status: 200 for URL: null
My service :
import { Headers, Http } from '#angular/http';
import 'rxjs/add/operator/toPromise';
export function createNonJsonResponse(http: Http, fullUrl: string): Promise<string>{
return http.get(fullUrl)
.toPromise()
.then(response => response.text())
// .catch(this.handleError);
}
I have logged both the URL given in and the Http and they are fine.
I have no idea why is this happening and google couldn't help me find any solutions whatsoever.
It seems, at least for me, #angular/core Http module is not working as intended. I switched to the nativescript's Http service (https://docs.nativescript.org/cookbook/http) and managed to accomplish what I needed without any problems.
Are you injecting the service somewhere? Add #Injectable() above the export. What if you change how you write the service a little and see if you receive the same response?
#Injectable()
export class createNonJsonResponse {
fullUrl: string = 'http://httpbin.org/get';
constructor(private http: Http) {}
getNonJsonResponse() {
return this.http.get(this.fullUrl)
.toPromise()
.then(response => response.text())
.catch(this.handleErrors);
}
}
Then import it to your component
import {createNonJsonResponse} from "./yourservicename.service"
And finally call it
this.createNonJsonResponse.getNonJsonResponse().then(function (data) {
alert("here");
//console.log(data);
//console.dump(data);
})
This worked for me I was able to hit my alert.

Hubot with slack adapter - cannot perform rtm.start

I'm trying to have hubot + slack on my local machine.
installed hubot and slack client.
running:
bin\hubot -a slack
and got error (after adding log messages to the script)
INFO Connecting...
INFO { ok: false, error: { [Error: socket hang up] code:
'ECONNRESET' } }
from reading code in node_modules\slack-client\src\client.js
found the problem occurs in a POST request:
Client.prototype.login = function() {
this.logger.info('Connecting...');
return this._apiCall('rtm.start', {
agent: 'node-slack'
}, this._onLogin); };
Client.prototype._apiCall = function(method, params, callback) {
var options, post_data, req;
params['token'] = this.token;
post_data = querystring.stringify(params);
options = {
hostname: this.host,
method: 'POST',
path: '/api/' + method,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': post_data.length
}
};
req = https.request(options);
tried to do: Node.js POST causes [Error: socket hang up] code: 'ECONNRESET'
with no success

Resources