Missing or insufficient permissions. request.auth seems to be null - firebase

I implemented the following security rules:
match /client/{clientId} {
allow read: if request.auth != null;
allow update, delete,create : if request.auth != null && request.auth.uid == clientId;
//allow create: if request.auth != null;
match /notifications/{notificationId} {
allow read,delete,update: if request.auth != null && request.auth.uid == clientId;
}
match /pointsHistory/{pointHistoryId} {
allow read,create: if request.auth != null && request.auth.uid == clientId;
}
match /subscribedTopics/{subscribedTopicId} {
allow read,create,delete: if request.auth != null && request.auth.uid == clientId;
}
match /userSavedAlerts/{userSavedAlertId} {
allow read,write: if request.auth != null && request.auth.uid == clientId;
}
match /userSavedPosts/{userSavedPostId} {
allow read,write: if request.auth != null && request.auth.uid == clientId;
}
}
On my app.js I added this to check if a user is already logged in:
const unlisten = auth().onAuthStateChanged((user) => {
if (user && auth().currentUser) {
setUserAuthData(user);
var db = firebase.firestore();
var docClientRef = db.collection("client").doc(auth().currentUser.uid);
docClientRef
.get()
.then((clientDoc) => {
if (clientDoc.exists) {
console.log("client doc exists: ", clientDoc.data());
const userData = clientDoc.data();
}
// getting “Missing or insufficient permissions.” Trying to read from clients collections
})
.catch((error) => {
console.log("error ", error);
});
}
return () => {
unlisten();
};
}, []);
I get the following error message: Missing or insufficient permissions. request.auth seems to be null. How can I resolve this error? I checked other stack overflow answers but nothing helped. Auth is seems to be null for firebase. I tested release app on TestFlight and debug on Xcode on iPhone device. Nothing works
Edit: printing the onauthstatechanged:
'user onUserChanged', { _auth:
{ _app:
{ _name: '[DEFAULT]',
_deleted: false,
_deleteApp: [Function: bound deleteApp],
_options:
{ databaseURL: '***********',
projectId: '*******',
gaTrackingId: null,
appId: '********************',
messagingSenderId: '***********',
apiKey: '*****************',
storageBucket: '********' },
_automaticDataCollectionEnabled: true,
_initialized: true,
_nativeInitialized: true },
_nativeModule:
{ createUserWithEmailAndPassword: [Function],
linkWithCredential: [Function],
reauthenticateWithCredential: [Function],
signInAnonymously: [Function],
signInWithCredential: [Function],
signInWithCustomToken: [Function],
signInWithEmailAndPassword: [Function],
signInWithEmailLink: [Function],
updatePhoneNumber: [Function],
addAuthStateListener: [Function],
addIdTokenListener: [Function],
applyActionCode: [Function],
checkActionCode: [Function],
confirmPasswordReset: [Function],
confirmationResultConfirm: [Function],
delete: [Function],
fetchSignInMethodsForEmail: [Function],
getIdToken: [Function],
getIdTokenResult: [Function],
reload: [Function],
removeAuthStateListener: [Function],
removeIdTokenListener: [Function],
sendEmailVerification: [Function],
sendPasswordResetEmail: [Function],
sendSignInLinkToEmail: [Function],
setAutoRetrievedSmsCodeForPhoneNumber: [Function],
setLanguageCode: [Function],
setTenantId: [Function],
signInWithPhoneNumber: [Function],
signOut: [Function],
unlink: [Function],
updateEmail: [Function],
updatePassword: [Function],
updateProfile: [Function],
useDeviceLanguage: [Function],
useEmulator: [Function],
verifyBeforeUpdateEmail: [Function],
verifyPasswordResetCode: [Function],
verifyPhoneNumber: [Function],
APP_USER:
{ '[DEFAULT]':
{ metadata: { lastSignInTime: 1652986981780, creationTime: 1609348971231 },
providerData:
[ { email: '*****#gmail.com',
phoneNumber: null,
photoURL: '*************',
displayName: '**** ****',
uid: '107327466708257974027',
providerId: 'google.com' } ],
phoneNumber: null,
photoURL: '********',
displayName: '*** ***',
email: '****#gmail.com',
uid: 'W81uqWYK6SOfl6ZC1yKPqgOAU382',
tenantId: null,
isAnonymous: false,
emailVerified: true,
providerId: 'firebase' } },
APP_LANGUAGE: { '[DEFAULT]': null },
getConstants: [Function] },
_customUrlOrRegion: undefined,
_config:
{ statics:
{ AppleAuthProvider: [Function: AppleAuthProvider],
EmailAuthProvider: [Function: EmailAuthProvider],
PhoneAuthProvider: [Function: PhoneAuthProvider],
GoogleAuthProvider: [Function: GoogleAuthProvider],
GithubAuthProvider: [Function: GithubAuthProvider],
TwitterAuthProvider: [Function: TwitterAuthProvider],
FacebookAuthProvider: [Function: FacebookAuthProvider],
OAuthProvider: [Function: OAuthProvider],
PhoneAuthState:
{ CODE_SENT: 'sent',
AUTO_VERIFY_TIMEOUT: 'timeout',
AUTO_VERIFIED: 'verified',
ERROR: 'error' } }

Related

Supabase JS reponse no data property

I tried to configure a next js project with supabase
But the data I receive is not consistent
To do this I have configured the following 3 files :
.env.local
NEXT_PUBLIC_SUPABASE_URL= ********
NEXT_PUBLIC_SUPABASE_ANON_KEY= ********
supabase.js
import { createClient } from '#supabase/supabase-js'
const supabase = createClient(
process.env.NEXT_PUBLIC_SUPABASE_URL,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY
)
export default supabase;
pages/api/posts.js
import supabase from '../../utils/supabase';
export default function handler(req, res) {
const posts = supabase.from("posts").select("*");
res.status(200).json(posts);
}
When I console log my posts variable, I have no data property.
It returned this,
PostgrestFilterBuilder {
fetch: [Function (anonymous)],
shouldThrowOnError: false,
allowEmpty: false,
url: URL {
href: '********/rest/v1/posts?select=*',
origin: '********',
protocol: 'https:',
username: '',
password: '',
host: '********',
hostname: '********',
port: '',
pathname: '/rest/v1/posts',
search: '?select=*',
searchParams: URLSearchParams { 'select' => '*' },
hash: ''
},
headers: {
'X-Client-Info': 'supabase-js/1.35.4',
apikey: '********',
Authorization: 'Bearer ********'
},
schema: 'public',
_subscription: null,
_realtime: RealtimeClient {
accessToken: null,
channels: [],
endPoint: 'wss://********/realtime/v1/websocket',
headers: { 'X-Client-Info': 'supabase-js/1.35.4' },
params: {
apikey: '********'
},
timeout: 10000,
transport: [Function: W3CWebSocket],
heartbeatIntervalMs: 30000,
longpollerTimeout: 20000,
heartbeatTimer: undefined,
pendingHeartbeatRef: null,
ref: 0,
logger: [Function: noop],
conn: null,
sendBuffer: [],
serializer: Serializer { HEADER_LENGTH: 1 },
stateChangeCallbacks: { open: [], close: [], error: [], message: [] },
reconnectAfterMs: [Function (anonymous)],
encode: [Function (anonymous)],
decode: [Function: bound decode],
reconnectTimer: Timer {
callback: [Function (anonymous)],
timerCalc: [Function (anonymous)],
timer: undefined,
tries: 0
}
},
_headers: {
'X-Client-Info': 'supabase-js/1.35.4',
apikey: '********',
Authorization: 'Bearer ********'
},
_schema: 'public',
_table: 'posts',
method: 'GET',
cs: [Function: contains],
cd: [Function: containedBy],
sl: [Function: rangeLt],
sr: [Function: rangeGt],
nxl: [Function: rangeGte],
nxr: [Function: rangeLte],
adj: [Function: rangeAdjacent],
ov: [Function: overlaps]
}
Also when I look at the dashboard of my supabase database I see that no query is receive
It seems that this query is not sent to the supabase API but I have no idea why ?
You need to await the Promise: https://supabase.com/docs/reference/javascript/select
import supabase from '../../utils/supabase';
export default async function handler(req, res) {
const posts = await supabase.from("posts").select("*");
res.status(200).json(posts);
}

NextJs and Socket IO is not connecting

I am trying to create a SocketIO solution with NextJS as below:
folder: api/socket.js
import { Server } from "socket.io";
const ioHandler = (req, res) => {
if (!res.socket.server.io) {
console.log("*First use, starting socket.io");
const io = new Server(res.socket.server);
io.on("connection", (socket) => {
console.log("Connected socket.io");
socket.broadcast.emit("a user connected");
socket.on("hello", (msg) => {
socket.emit("hello", "world!");
});
});
res.socket.server.io = io;
} else {
console.log("socket.io already running");
}
res.end();
};
export const config = {
api: {
bodyParser: false,
},
};
export default ioHandler;
folder: api/test.js
import io from "socket.io-client";
fetch("http://localhost:3000/api/socket");
const socket = io();
console.log(socket.connection);
socket.on("connect", () => {
console.log("connected");
});
But when I run api/test.js the SocketIO is not connected as below:
Socket {
connected: false,
receiveBuffer: [],
sendBuffer: [],
ids: 0,
acks: {},
flags: {},
io: Manager {
nsps: { '//undefined//undefined': [Circular *1] },
subs: [
[Function: subDestroy],
[Function: subDestroy],
[Function: subDestroy]
],
opts: {
path: '/socket.io',
hostname: 'undefined',
secure: false,
port: '80'
},
setTimeoutFn: [Function: bound setTimeout],
clearTimeoutFn: [Function: bound clearTimeout],
_reconnection: true,
_reconnectionAttempts: Infinity,
_reconnectionDelay: 1000,
_reconnectionDelayMax: 5000,
_randomizationFactor: 0.5,
backoff: Backoff {
ms: 1000,
max: 5000,
factor: 2,
jitter: 0.5,
attempts: 0
},
_timeout: 20000,
_readyState: 'opening',
uri: 'undefined//undefined//undefined',
encoder: Encoder { replacer: undefined },
decoder: Decoder { reviver: undefined },
_autoConnect: true,
engine: Socket {
setTimeoutFn: [Function: bound setTimeout],
clearTimeoutFn: [Function: bound clearTimeout],
secure: false,
hostname: 'undefined',
port: '80',
transports: [Array],
readyState: 'opening',
writeBuffer: [],
prevBufferLen: 0,
opts: [Object],
id: null,
upgrades: null,
pingInterval: null,
pingTimeout: null,
pingTimeoutTimer: null,
transport: [Polling],
_callbacks: [Object]
},
skipReconnect: false,
_callbacks: {
'$open': [Array],
'$packet': [Array],
'$error': [Array],
'$close': [Array]
}
},
nsp: '//undefined//undefined',
subs: [
[Function: subDestroy],
[Function: subDestroy],
[Function: subDestroy],
[Function: subDestroy]
]
}
Any suggestions?
According to documentation socket server options here socket.io v4
you need to specify a path same as client path
in your case
const io = new Server(res.socket.server, {path:'/api/socket'});

Next JS : Failed to collect page data for when build on VPS

I have Next JS Application already hosted in VPS and data fetching using GetStaticProps and GetStaticPaths, then this application will consume REST Api from my subdomain with same VPS.
Next JS Application : http://zeffry.my.id
Rest API http://admin.zeffry.my.id/api
When i running npm run build on VPS, I get an error which indicates it is related to getStaticPaths.
zeffry#zeffryportofolio:/var/www/zeffry-reynando$ npm run build
> zeffry-reynando#0.1.0 build
> next build
info - Loaded env from /var/www/zeffry-reynando/.env
info - SWC minify release candidate enabled. https://nextjs.link/swcmin
info - Linting and checking validity of types
info - Creating an optimized production build
info - Compiled successfully
info - Collecting page data ..[AxiosError: Request failed with status code 400] {
code: 'ERR_BAD_REQUEST',
config: {
transitional: {
silentJSONParsing: true,
forcedJSONParsing: true,
clarifyTimeoutError: false
},
adapter: [Function: httpAdapter],
transformRequest: [ [Function: transformRequest] ],
transformResponse: [ [Function: transformResponse] ],
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
maxBodyLength: -1,
env: { FormData: [Function] },
validateStatus: [Function: validateStatus],
headers: {
Accept: 'application/json, text/plain, */*',
'User-Agent': 'axios/0.27.2'
},
method: 'get',
url: "'http://admin.zeffry.my.id/api';/portfolio",
data: undefined
},
request: <ref *1> ClientRequest {
_events: [Object: null prototype] {
abort: [Function (anonymous)],
aborted: [Function (anonymous)],
connect: [Function (anonymous)],
error: [Function (anonymous)],
socket: [Function (anonymous)],
timeout: [Function (anonymous)],
prefinish: [Function: requestOnPrefinish]
},
_eventsCount: 7,
_maxListeners: undefined,
outputData: [],
outputSize: 0,
writable: true,
destroyed: false,
_last: true,
chunkedEncoding: false,
shouldKeepAlive: false,
maxRequestsOnConnectionReached: false,
_defaultKeepAlive: true,
useChunkedEncodingByDefault: false,
sendDate: false,
_removedConnection: false,
_removedContLen: false,
_removedTE: false,
_contentLength: 0,
_hasBody: true,
_trailer: '',
finished: true,
_headerSent: true,
_closed: false,
socket: Socket {
connecting: false,
_hadError: false,
_parent: null,
_host: 'localhost',
_readableState: [ReadableState],
_events: [Object: null prototype],
_eventsCount: 7,
_maxListeners: undefined,
_writableState: [WritableState],
allowHalfOpen: false,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: null,
_server: null,
parser: null,
_httpMessage: [Circular *1],
[Symbol(async_id_symbol)]: 13,
[Symbol(kHandle)]: [TCP],
[Symbol(lastWriteQueueSize)]: 0,
[Symbol(timeout)]: null,
[Symbol(kBuffer)]: null,
[Symbol(kBufferCb)]: null,
[Symbol(kBufferGen)]: null,
[Symbol(kCapture)]: false,
[Symbol(kSetNoDelay)]: false,
[Symbol(kSetKeepAlive)]: true,
[Symbol(kSetKeepAliveInitialDelay)]: 60,
[Symbol(kBytesRead)]: 0,
[Symbol(kBytesWritten)]: 0,
[Symbol(RequestTimeout)]: undefined
},
_header: 'GET %27http://admin.zeffry.my.id/api%27;/portfolio HTTP/1.1\r\n' +
'Accept: application/json, text/plain, */*\r\n' +
'User-Agent: axios/0.27.2\r\n' +
'Host: localhost\r\n' +
'Connection: close\r\n' +
'\r\n',
_keepAliveTimeout: 0,
_onPendingData: [Function: nop],
agent: Agent {
_events: [Object: null prototype],
_eventsCount: 2,
_maxListeners: undefined,
defaultPort: 80,
protocol: 'http:',
options: [Object: null prototype],
requests: [Object: null prototype] {},
sockets: [Object: null prototype],
freeSockets: [Object: null prototype] {},
keepAliveMsecs: 1000,
keepAlive: false,
maxSockets: Infinity,
maxFreeSockets: 256,
scheduling: 'lifo',
maxTotalSockets: Infinity,
totalSocketCount: 1,
[Symbol(kCapture)]: false
},
socketPath: undefined,
method: 'GET',
maxHeaderSize: undefined,
insecureHTTPParser: undefined,
path: '%27http://admin.zeffry.my.id/api%27;/portfolio',
_ended: true,
res: IncomingMessage {
_readableState: [ReadableState],
_events: [Object: null prototype],
_eventsCount: 4,
_maxListeners: undefined,
socket: [Socket],
httpVersionMajor: 1,
httpVersionMinor: 1,
httpVersion: '1.1',
complete: true,
rawHeaders: [Array],
rawTrailers: [],
aborted: false,
upgrade: false,
url: '',
method: null,
statusCode: 400,
statusMessage: 'Bad Request',
client: [Socket],
_consuming: false,
_dumped: false,
req: [Circular *1],
responseUrl: '%27http://admin.zeffry.my.id/api%27;/portfolio',
redirects: [],
[Symbol(kCapture)]: false,
[Symbol(kHeaders)]: [Object],
[Symbol(kHeadersCount)]: 10,
[Symbol(kTrailers)]: null,
[Symbol(kTrailersCount)]: 0,
[Symbol(RequestTimeout)]: undefined
},
aborted: false,
timeoutCb: null,
upgradeOrConnect: false,
parser: null,
maxHeadersCount: null,
reusedSocket: false,
host: 'localhost',
protocol: 'http:',
_redirectable: Writable {
_writableState: [WritableState],
_events: [Object: null prototype],
_eventsCount: 3,
_maxListeners: undefined,
_options: [Object],
_ended: true,
_ending: true,
_redirectCount: 0,
_redirects: [],
_requestBodyLength: 0,
_requestBodyBuffers: [],
_onNativeResponse: [Function (anonymous)],
_currentRequest: [Circular *1],
_currentUrl: '%27http://admin.zeffry.my.id/api%27;/portfolio',
[Symbol(kCapture)]: false
},
[Symbol(kCapture)]: false,
[Symbol(kNeedDrain)]: false,
[Symbol(corked)]: 0,
[Symbol(kOutHeaders)]: [Object: null prototype] {
accept: [Array],
'user-agent': [Array],
host: [Array]
},
[Symbol(kUniqueHeaders)]: null
},
response: {
status: 400,
statusText: 'Bad Request',
headers: {
server: 'nginx/1.18.0 (Ubuntu)',
date: 'Fri, 02 Sep 2022 11:48:55 GMT',
'content-type': 'text/html',
'content-length': '166',
connection: 'close'
},
config: {
transitional: [Object],
adapter: [Function: httpAdapter],
transformRequest: [Array],
transformResponse: [Array],
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
maxBodyLength: -1,
env: [Object],
validateStatus: [Function: validateStatus],
headers: [Object],
method: 'get',
url: "'http://admin.zeffry.my.id/api';/portfolio",
data: undefined
},
request: <ref *1> ClientRequest {
_events: [Object: null prototype],
_eventsCount: 7,
_maxListeners: undefined,
outputData: [],
outputSize: 0,
writable: true,
destroyed: false,
_last: true,
chunkedEncoding: false,
shouldKeepAlive: false,
maxRequestsOnConnectionReached: false,
_defaultKeepAlive: true,
useChunkedEncodingByDefault: false,
sendDate: false,
_removedConnection: false,
_removedContLen: false,
_removedTE: false,
_contentLength: 0,
_hasBody: true,
_trailer: '',
finished: true,
_headerSent: true,
_closed: false,
socket: [Socket],
_header: 'GET %27http://admin.zeffry.my.id/api%27;/portfolio HTTP/1.1\r\n' +
'Accept: application/json, text/plain, */*\r\n' +
'User-Agent: axios/0.27.2\r\n' +
'Host: localhost\r\n' +
'Connection: close\r\n' +
'\r\n',
_keepAliveTimeout: 0,
_onPendingData: [Function: nop],
agent: [Agent],
socketPath: undefined,
method: 'GET',
maxHeaderSize: undefined,
insecureHTTPParser: undefined,
path: '%27http://admin.zeffry.my.id/api%27;/portfolio',
_ended: true,
res: [IncomingMessage],
aborted: false,
timeoutCb: null,
upgradeOrConnect: false,
parser: null,
maxHeadersCount: null,
reusedSocket: false,
host: 'localhost',
protocol: 'http:',
_redirectable: [Writable],
[Symbol(kCapture)]: false,
[Symbol(kNeedDrain)]: false,
[Symbol(corked)]: 0,
[Symbol(kOutHeaders)]: [Object: null prototype],
[Symbol(kUniqueHeaders)]: null
},
data: '<html>\r\n' +
'<head><title>400 Bad Request</title></head>\r\n' +
'<body>\r\n' +
'<center><h1>400 Bad Request</h1></center>\r\n' +
'<hr><center>nginx/1.18.0 (Ubuntu)</center>\r\n' +
'</body>\r\n' +
'</html>\r\n'
}
}
> Build error occurred
Error: Failed to collect page data for /portfolio/[slug]
at /var/www/zeffry-reynando/node_modules/next/dist/build/utils.js:743:15
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
type: 'Error'
}
This line indicate the rror :
export const getStaticProps: GetStaticProps = async (context) => {
try {
const { slug } = context.params as IParams;
const url =
process.env["NODE_ENV"] == "development"
? process.env["BASE_API_LOCALHOST_URL"]
: process.env["BASE_API_URL"];
const portfolio = await axios.get(`${url}/portfolio/${slug}`);
if (!portfolio.data.data) throw "Data tidak ditemukan";
const data: PortfolioDetailInterface = portfolio.data.data;
const props = {
portfolio: data,
};
return {
props: props,
};
} catch (error) {
return {
notFound: true,
};
}
};
export const getStaticPaths: GetStaticPaths = async (context) => {
const url =
process.env["NODE_ENV"] == "development"
? process.env["BASE_API_LOCALHOST_URL"]
: process.env["BASE_API_URL"];
const portfolio = await axios.get(`${url}/portfolio`);
const arrPortfolio: PortfolioInterface[] = portfolio.data.data;
const slug = arrPortfolio.map(function (val) {
return {
params: {
slug: val.title_slug,
},
};
});
return {
paths: slug,
fallback: "blocking",
};
};
export default PortfolioDetailPage;
I can confirm that when testing on my local machine, the application runs smoothly without any problems.
If you access this endpoint http://admin.zeffry.my.id/api/portfolio/amerta, response is
// 20220902190903
// http://admin.zeffry.my.id/api/portfolio/amerta
{
"success": true,
"data": {
"id": 1,
"type_application_id": 11,
"main_technology_id": 15,
"title": "Amerta",
"title_slug": "amerta",
"short_description": "amerta",
"full_description": "<p>amerta</p>",
"banner_image": "http://admin.zeffry.my.id/storage/images/portfolio/banner/6311b9c0e52cc1662106048.png",
"github_url": null,
"web_url": null,
"google_playstore_url": null,
"app_store_url": null,
"created_at": "2022-09-02T08:07:30.000000Z",
"updated_at": "2022-09-02T08:07:30.000000Z",
"created_by": null,
"updated_by": null,
"previewImages": [
{
"id": "c9a51e0b-4357-44a5-9b92-07f404050561",
"portfolio_id": 1,
"image": "http://admin.zeffry.my.id/storage/images/portfolio/preview/6311b9c2c9b281662106050.png"
}
],
"main_technology": {
"id": 15,
"name": "Flutter"
},
"type": {
"id": 11,
"name": "Mobile Apps"
},
"other_technology": [
{
"id": "faaf2db5-1c0c-4c05-8fa9-3da43fb4e2ce",
"portfolio_id": 1,
"technology_id": 15,
"technology": {
"id": 15,
"name": "Flutter"
}
}
],
"preview_images": [
{
"id": "c9a51e0b-4357-44a5-9b92-07f404050561",
"portfolio_id": 1,
"image": "http://admin.zeffry.my.id/storage/images/portfolio/preview/6311b9c2c9b281662106050.png"
}
]
}
}
Are there any settings for deploying missing?

request-promise not recognizing the URI when it is stated in the option object

I have a method that should return a response from another server. I use request-promise and put the URL in the options object.
As you can see in the code below, all is in good shape, but when I send the request, it returns 404 - resource not found.
When I change the request(options) method with request("https://api.quickpay.net/payments"), I get a positive answer from the server -- it tells me to add headers and so forth, which is positive.
public requestNewQuickpayPayment(order_id: String, currency : String, callback: Function) {
var options = {
method: 'POST',
uri: 'https://api.quickpay.net/payments',
form:{
order_id : "order123",
currency : "dkk"
},
headers: {
"Content-Type" : "application/json",
'Accept-Version': 'v10'
},
json: true
};
request(options).then((response:any)=>{
console.log(response);
return response;
}).catch((error:any)=>{
console.log(error);
return error;
}).finally(()=>{
console.log("done");
})
}
Something from the console
Request {
_events: [Object],
_eventsCount: 5,
_maxListeners: undefined,
method: 'POST',
uri: [Url],
transform2xxOnly: true,
headers: [Object],
readable: true,
writable: true,
explicitMethod: true,
_qs: [Querystring],
_auth: [Auth],
_oauth: [OAuth],
_multipart: [Multipart],
_redirect: [Redirect],
_tunnel: [Tunnel],
_rp_resolve: [Function],
_rp_reject: [Function],
_rp_promise: [Promise],
_rp_callbackOrig: undefined,
callback: [Function],
_rp_options: [Object],
setHeader: [Function],
hasHeader: [Function],
getHeader: [Function],
removeHeader: [Function],
localAddress: undefined,
pool: {},
dests: [],
__isRequestRequest: true,
_callback: [Function: RP$callback],
proxy: null,
tunnel: true,
setHost: true,
originalCookieHeader: undefined,
_disableCookies: true,
_jar: undefined,
port: 443,
host: 'api.quickpay.net',
body: 'order_id=asdasdasd&currency=dkk',
path: '/payments',
_json: true,
httpModule: [Object],
agentClass: [Function],
agent: [Agent],
_started: true,
href: 'https://api.quickpay.net/payments',
req: [ClientRequest],
ntick: true,
response: [Circular],
originalHost: 'api.quickpay.net',
originalHostHeaderName: 'host',
responseContent: [Circular],
_destdata: true,
_ended: true,
_callbackCalled: true },
toJSON: [Function: responseToJSON],
caseless: Caseless { dict: [Object] },
body: '404 Not Found' } }
What is wrong here? The path to the ressource is checked many times - nothing is wrong there....
For api.quickpay.net, 404 Not Found does not mean the URI is not recognized, but indicating invalid request body. It has nothing to do with whether the URI is stated in options object, or stated as string parameter of request().
Here is a simple experiment. The code below would return "positive" result, warning missing headers ({"error":"Accept-Version http header is required"}), which indicates that the URI is "recognized":
request({
method: 'POST',
uri: 'https://api.quickpay.net/payments'
}, function(err, res, body) {
console.log(body);
});
However, after the missing Accept-Version header is added, we get 404 Not Found:
request({
method: 'POST',
uri: 'https://api.quickpay.net/payments',
headers: {
'Accept-Version': 'v10'
}
}, function(err, res, body) {
console.log(body);
});
Thus, in order to make the API call work, you need to make the HTTP request valid (following to the document).

fetch doesn't work in jest, and return TypeError: Network request failed

I am trying to migrate from karma + PhantomJS to Jest + jsDom, but I got a problem. all fetch in UT failed in Jest. I am trying to figure out the reason. So I just write a simple UT like this
import fetch from 'isomorphic-fetch';
import $ from 'jquery';
describe('test', () => {
it('should fetch success....', (done) => {
return fetch('http://www.ebay.com/', { method: 'get' })
.then((res) => {
console.log(res);
done();
})
.catch(err => console.log(err));
})
it('should get success....', (done) => {
$.get('http://www.ebay.com/', (res) => {
console.log(res);
done();
}).fail((xhr, statusText, err) => {
console.log(statusText, err);
})
})
})
but still get the error like this
TypeError: Network request failed
at XMLHttpRequest.xhr.onerror (/Users/davidhe/work/activenet/git/aui/node_modules/whatwg-fetch/fetch.js:436:16)
at XMLHttpRequest.callback.(anonymous function) (/Users/davidhe/work/activenet/git/aui/node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/living/events/EventTa
rget-impl.js:289:32)
at invokeEventListeners (/Users/davidhe/work/activenet/git/aui/node_modules/jest-environment-jsdom/node_modules/jsdo
m/lib/jsdom/living/events/EventTarget-impl.js:219:27)
at invokeInlineListeners (/Users/davidhe/work/activenet/git/aui/node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:166:7)
at EventTargetImpl._dispatch (/Users/davidhe/work/activenet/git/aui/node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:122:7)
at EventTargetImpl.dispatchEvent (/Users/davidhe/work/activenet/git/aui/node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:87
:17)
at XMLHttpRequest.dispatchEvent (/Users/davidhe/work/activenet/git/aui/node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/living/generated/EventTarget.js:61:35
)
at dispatchError (/Users/davidhe/work/activenet/git/aui/node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/living/xmlhttprequest.js:994:9)
at validCORSHeaders (/Users/davidhe/work/activenet/git/aui/node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/living/xmlhttprequest.js:1009:7)
at receiveResponse (/Users/davidhe/work/activenet/git/aui/node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/living/xmlhttprequest.js:871:12)
at Request.client.on.res (/Users/davidhe/work/activenet/git/aui/node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/living/xmlhttprequest.js:691:38)
at emitOne (events.js:96:13)
at Request.emit (events.js:188:7)
at Request.onRequestResponse (/Users/davidhe/work/activenet/git/aui/node_modules/request/request.js:1074:10)
at emitOne (events.js:96:13)
at ClientRequest.emit (events.js:188:7)
at HTTPParser.parserOnIncomingClient [as onIncoming] (_http_client.js:473:21)
at HTTPParser.parserOnHeadersComplete (_http_common.js:99:23)
at Socket.socketOnData (_http_client.js:362:20)
at emitOne (events.js:96:13)
at Socket.emit (events.js:188:7)
at readableAddChunk (_stream_readable.js:176:18)
at Socket.Readable.push (_stream_readable.js:134:10)
at TCP.onread (net.js:547:20)
this is my package.json
{
devDependencies:{
"jsdom": "^11.0.0",
"babel-jest": "^20.0.3",
"jest": "^20.0.4"
},
"dependencies": {
"isomorphic-fetch": "^2.2.1"
}
"jest": {
"browser": true,
"testEnvironment": "jsdom",
"cacheDirectory": "./node_modules/.cache",
"verbose": true,
"globals": {
"__STATIC__": true,
"__DEV__": false,
"__TESTING__": true
},
"transformIgnorePatterns": [
"/node_modules/(?!react-aaui).+\\.js$"
],
"moduleNameMapper": {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/test/__mocks__/fileMock.js",
"\\.(css|less)$": "<rootDir>/test/__mocks__/styleMock.js",
"^imports": "<rootDir>/test/__mocks__/jestImportsMock.js"
},
"testRegex": "(fetch\\.(test|spec))\\.(jsx|js)$",
"moduleFileExtensions": [
"json",
"jsx",
"js"
],
"moduleDirectories": [
"node_modules",
"src",
"test"
],
"modulePathIgnorePatterns": [],
"snapshotSerializers": [
"enzyme-to-json/serializer"
],
"collectCoverage": false,
"collectCoverageFrom": [
"src/**/*.{js,jsx}",
"!**/__mocks__/**"
],
"coverageReporters": [
"text",
"html"
],
"coverageDirectory": "test/coverage",
"setupFiles": [
"./test/tests.initialState.jest.js"
],
"testPathIgnorePatterns": [
"/node_modules/",
"/examples/",
"/dist/"
]
}
}
Anyone can help me on it.
I encounter the same issue. And I use fetch-mock to solve it nicely.
import fetchMock from 'fetch-mock'
it ("normally should return success", () => {
fetchMock.getOnce('*', {user: 'ron'})
expect(fetch('http://your.example.com').then(x=>x.json())
.resolves.toEqual({user: 'ron})
})
this question is resolved by add
import { XMLHttpRequest } from 'xmlhttprequest';
global.XMLHttpRequest = XMLHttpRequest;
in tests.initialState.jest.js.
before, I was using w3c-xmlhttprequest, and it doesn't work.
In my case adding the full Url, it didn't show the error.
const login = rest.post('http://localhost:3001/api/auth/login', (req, res, ctx) => {

Resources