React axios JSON.stringify() use to [Object object] -> "[Object object]" - javascript

i'm junior fronted developer, and i want to your help...
below my pages code
const sendAnotherIp = async () => {
const domain_format = /^(((http(s?))\:\/\/)?)([0-9a-zA-Z\-]+\.)+[a-zA-Z]{2,6}(\:[0-9]+)?(\/\S*)?/;
if (domain_format.test(anotherIp)) {
await axios
.get(`${process.env.NEXT_PUBLIC_CLIENT_URL}/api/dnslookup`, {
params: {
search: anotherIp,
date: nowTime,
},
})
.then((res) => {
alert(res.data);
});
} else {
alert("it's wrong domain format");
}
};
console.log(JSON.stringify(data)); -> "[Object object]"
below my api code
import { NextApiRequest, NextApiResponse } from "next";
const sqlite3 = require("sqlite3").verbose();
const dns = require("dns");
interface Iquerys {
search: string;
date: string;
}
interface IUrl {
ip: string;
}
const dnslookup = (request: NextApiRequest, response) => {
const req = response.req;
const querys: Iquerys = req.query;
const searchData = querys.search;
const dateData = querys.date;
// below my logic
response.status(200).end(
`${dns.resolveAny(searchData, function (err: any, addresses: any) {
return addresses;
})}`
);
//
// db connect
let db = new sqlite3.Database("./db/my_database.db", (err) => {
if (err) {
return console.log(err.message);
}
console.log("Connected to database!");
});
// db peristalsis
db.run("INSERT INTO DnsLookup(search, date) VALUES (?, ?)", [searchData, dateData], (err) => {
if (err) {
return console.log(err.message);
}
console.log("Row was added to the table: ${this.lastID}");
});
};
export default dnslookup;
my project build in react, next js.
I used to JSON.parse() and JSON.stringify() and toString() ... etc
but I can't find a way to real data.
what's wrong with my code? help me please guys

I think the server code is the problem. You should wait for the call back to complete then you should send the response.
response.status(200).end(
`${dns.resolveAny(searchData, function (err: any, addresses: any) {
return addresses;
})}`
);
On the front end code, you should remove await in front of Axios that is not needed.

First declare the headers to be Application/Json
axios.get('m', {
headers: {
'Content-Type': 'application/json'
}
})

Related

How to improve sequential promises execution and force fulfillment

This code is being used in a Sveltekit web application.
In the first step I get a user jwt token from an api like : dashboard.example.com/auth/local
and in the second step I'm using the response of the first api call to get full information from an api endpoint like this : example.com/api/users/token
This is an endpoint in an Sveltekit application:
import { json as json$1, error } from '#sveltejs/kit';
import axios from 'axios';
import md5 from 'md5';
import { SITE_ADDRESS } from '$lib/Env';
let userToken;
/** #type {import('#sveltejs/kit').RequestHandler} */
export async function POST({ request }) {
const bodyData = await request.json();
let identifier = bodyData.data.identifier;
let password = bodyData.data.password;
let loginToken = bodyData.data.loginToken;
let newLoginToken = md5(identifier + password + process.env.SECURE_HASH_TOKEN);
let dataResult = await axios
.post(`${import.meta.env.VITE_SITE_API}/auth/local`, {
identifier: identifier,
password: password
})
.then((response) => {
return response.data;
})
.then((response) => {
let userSummaryData = response;
userToken = md5(
userSummaryData.user.username + userSummaryData.user.id + process.env.SECURE_HASH_TOKEN
);
let userCompleteData = axios
.post(`${SITE_ADDRESS}/api/users/${userToken}`, {
data: {
userID: userSummaryData.user.id,
username: userSummaryData.user.username
}
})
.then((response) => {
return {
userJWT: userSummaryData.jwt,
userSummary: userSummaryData.user,
userFullSummary: response.data.userFullSummary
};
});
return userCompleteData;
})
.catch((error) => {
// console.log(' ---- Err ----');
});
if (dataResult && newLoginToken == loginToken) {
return json$1(
{
userJWT: dataResult.userJWT,
userSummary: dataResult.userSummary,
userFullSummary: dataResult.userFullSummary
},
{
headers: {
'cache-control': 'private, max-age=0, no-store'
}
}
);
} else if (dataResult && newLoginToken != loginToken) {
throw error(400, 'Something wrong happened');
}
throw error(401, 'Something wrong happened');
}
This code is work perfectly in localhost. But when I test it on host I get error 401.
and the question is :
Why this works on localhost but doesn't work on the server?
How can I improve this kind of promises (I'd like to use the response of the first api call in the second api call and return both
as a result)

Stripe webhook nodejs remix.run Stripe webhook - No signatures found matching the expected signature for payload

Could someone help me please. Do I need to convert the request body into raw json type?
I'm using remix.run to create an endpoint for the stripe webhook. I'm getting an error:
No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe? https://github.com/stripe/stripe-node#webhook-signing - but I don't know how to convert the req.body into raw?
import type { ActionFunction } from "#remix-run/node";
import stripe from "stripe";
export const action: ActionFunction = async ({ request }) => {
switch (request.method) {
case "POST": {
const endpointSecret =
"whsec_abxxxxaf67fxxxa955";
console.log("Header", request.headers.get("stripe-signature"));
const sig: any = request.headers.get("stripe-signature");
console.log("--sig", sig);
let event;
try {
event = stripe.webhooks.constructEvent(
request.body,
sig,
endpointSecret
);
console.log("event", event);
return null;
} catch (err) {
console.log("err", err);
return null;
}
}
}
return null;
};
export default () => {
return <p>FAILED</p>;
};
And the error that I'm getting.
{
type: 'StripeSignatureVerificationError',
raw: {
message: 'No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe? https://github.com/stripe/stripe-node#webhook-signing'
},
rawType: undefined,
code: undefined,
doc_url: undefined,
param: undefined,
detail: undefined,
headers: undefined,
requestId: undefined,
statusCode: undefined,
charge: undefined,
decline_code: undefined,
payment_intent: undefined,
payment_method: undefined,
payment_method_type: undefined,
setup_intent: undefined,
source: undefined,
header: 't=1669990993,v1=026c8a0xxxxxxxfc1048d1abc07,v0=85099acc2420c06bxxx22dd8553e60681befd59d238b4514cbdd',
payload: <ref *1> ReadableStream3 [ReadableStream]
My printed header is show the correct key, i think.
t=1669990993,v1=026c8a00b366cd657a2xxxxxxf5b003fc1048d1abc07,v0=85099acc2420c06bc0d2dxxx3e60681befd59d238b4514cbdd
It looks like you can get the raw request body with request.text() then use that in constructEvent.
const payload = await request.text()
...
event = stripe.webhooks.constructEvent(payload, sig, secret)
You can see this here, an example shared by a Stripe Developer Advocate here.
My working codes
import Stripe from "stripe";
import { insertIntoStripe } from "~/models/stripe.server";
import cuid from "cuid";
import { updatePaymentStatus } from "~/models/order.server";
import Plunk from "#plunk/node";
const stripe = new Stripe(process.env.STRIPE_API, {});
export const action = async ({ request }) => {
const sig = request.headers.get("stripe-signature");
let event;
const payload = await request.text();
try {
event = stripe.webhooks.constructEvent(
payload,
sig,
process.env.STRIPE_WEBHOOK_KEY
);
} catch (err) {
return new Response(err.message, {
status: 400,
});
}
if (event.type == "payment_intent.succeeded") {
const paymentIntentJson: any = event.data.object;
const paymentIntentID: any = paymentIntentJson.id;
const email: any = paymentIntentJson.charges.data[0].billing_details.email;
const name: any = paymentIntentJson.charges.data[0].billing_details.name;
const amount: any = paymentIntentJson.amount;
const sessionList = await stripe.checkout.sessions.list();
sessionList.data.map(async (session) => {
if (session.payment_intent == paymentIntentID) {
const client_reference_id: any = session.client_reference_id;
await insertIntoStripe(
cuid(),
paymentIntentID,
name,
email,
amount,
client_reference_id,
paymentIntentJson
);
await updatePaymentStatus(client_reference_id, "SUCCESS");
const plunk = new Plunk(process.env.USEPLUNK_EMAIL_API);
//send email
await plunk.events.publish({
email: email,
event: "send-completed-order-email",
data: {
orderId: client_reference_id,
},
});
}
return null;
});
console.log("💰 payment success!");
return new Response("Success", {
status: 200,
});
}
return new Response("Success", {
status: 200,
});
};

URQL WSS connection with GraphQL-WS says error 4500

import {
createClient,
defaultExchanges,dedupExchange, cacheExchange, fetchExchange,
subscriptionExchange,
gql
} from "#urql/core";
import { createClient as createWSClient } from "graphql-ws";
import { pipe, subscribe } from "wonka";
import { getToken, setToken } from "./helper";
const wsClient = createWSClient({
url: 'wss://**********/subscriptions',
reconnect: true,
});
const client = createClient({
url: "https://***********/",
fetchOptions: () => {
const token = getToken()
return token ? { headers: { authorization: `Bearer "${token}"` } } : {}
},
// the default:
exchanges: [
...defaultExchanges,
subscriptionExchange({
forwardSubscription(operation) {
return {
subscribe: (sink) => {
const dispose = wsClient.subscribe(operation, sink);
return {
unsubscribe: dispose,
};
},
};
},
}),
]
});
SUB_TO_MESSAGES = async () => {
console.log('sub')
const token = getToken();
console.log(String(token))
const { unsubscribe } = pipe(
await client.subscription(messageAdded,{ jwt: token }),
subscribe((result) => {
console.log(result)
})
)
};
I dont get the same issue with try and catch using GraphQL-WS but I still dont get any data from the server. The assignment is a vanillaJS project using GraphQL.I didndt post the url, jwt token,or the GET, POST, REgG as they work as intended. The rendering is done with a proxy. The error message is:
Connection Closed: 4500 Cannot read properties of undefined (reading 'Authorization')
Even playground doesnt work. Something wrong with the endpoint. It worked 2 weeks ago but admin says it still work yet I can find the problem. It used to work for me.
Here is the try and catch version:
import { createClient} from "graphql-ws";
import pStore from "./handler.js";
import { getToken } from "./helper";
const client = createClient({
url: "wss://******/subscriptions",
reconnect: true,
connectionParams:{
headers: {
"Authorization":`Bearer ${getToken()}`
}
},
})
async SUB_MESSAGE() {
try {
console.log('called Gql server')
const onNext = (res) => {
let obj = res.data.messageAdded
console.log(obj)
pStore[obj.id] = obj
pStore.render(obj)
};
let unsubscribe = () => {
/* complete the subscription */
};
new Promise((resolve, reject) => {
client.subscribe({
query: `subscription{messageAdded(jwt:"${getToken()}"){id text fromAgent createdAt updatedAt}}`,
},
{
next: (data)=> onNext(data),
error: reject,
complete: () => resolve(true),
})
})
}catch(error){
console.error('There has been a problem with your ws operation:', error);
}
}
Either way I think its a ad character, scope issue but I dont know where.

Express Mongoose API Factory

I'm trying to create API factory for node.js, Express, Mongoose Tech stack. I also want to provide full type safety using Typescript and the option to add additional validation for creation and updates. For example I have "validator" like that:
type ICheckIfUnique = <M, T extends Model<M>, K extends keyof M>(
attributes: {
model: T;
key: K;
},
body: M
) => void;
export const checkIfUnique: ICheckIfUnique = async (attributes, body) => {
const { model, key } = attributes;
const value = body[key];
const isUnique = !(await model.findOne({ [key]: value }));
if (!isUnique) {
throw `${key} is not unique!`;
}
};
But I can't get the type right as I get:
I can't also find way to get custom model types for the factory methods:
export const factoryCreateEndpoint =
<T, D extends Model<T>>(model: D, additionalLogic?: any) =>
async (req: Request, res: Response): Promise<Response | undefined> => {
const body = req.body;
if (!body) {
return res.status(400).json({
success: false,
error: `You must provide ${capitalize(
model.collection.name.slice(0, -1)
)}.`,
});
}
if (additionalLogic) {
try {
for (const element in additionalLogic) {
const { validator, additionalVariables } = additionalLogic[element];
await validator(additionalVariables, req.body);
}
} catch (error) {
return res.status(400).json({ success: false, error });
}
}
try {
const object = new model(body);
await object.save();
return res.status(201).json({
success: true,
id: object._id,
message: `${capitalize(model.collection.name.slice(0, -1))} created.`,
});
} catch (error) {
return res.status(400).json({ success: false, error });
}
};
But with this generic type I get:

Unsubscribe email using Fetch api Javascript

I have a form where i enter an email and it gets ''subscribed'' in a user.json file using a fetch api on node server.My task is to :
upon clicking on the "Unsubscribe" button, implement the functionality for unsubscribing from the community list. For that, make POST Ajax request using http://localhost:3000/unsubscribe endpoint.
I tried to make the function but it wasnt succeseful so i deleted it. Also,i need to do the following :
While the requests to http://localhost:3000/subscribe and
http://localhost:3000/unsubscribe endpoints are in progress, prevent
additional requests upon clicking on "Subscribe" and "Unsubscribe".
Also, disable them (use the disabled attribute) and style them using
opacity: 0.5.
For me ajax requests,fetch and javascript is something new,so i dont know really well how to do this task,if you could help me i'll be happy,thanks in advance.
fetch code for subscribing:
import { validateEmail } from './email-validator.js'
export const sendSubscribe = (emailInput) => {
const isValidEmail = validateEmail(emailInput)
if (isValidEmail === true) {
sendData(emailInput);
}
}
export const sendHttpRequest = (method, url, data) => {
return fetch(url, {
method: method,
body: JSON.stringify(data),
headers: data ? {
'Content-Type': 'application/json'
} : {}
}).then(response => {
if (response.status >= 400) {
return response.json().then(errResData => {
const error = new Error('Something went wrong!');
error.data = errResData;
throw error;
});
}
return response.json();
});
};
const sendData = (emailInput) => {
sendHttpRequest('POST', 'http://localhost:8080/subscribe', {
email: emailInput
}).then(responseData => {
return responseData
}).catch(err => {
console.log(err, err.data);
window.alert(err.data.error)
});
}
index.js from route node server:
const express = require('express');
const router = express.Router();
const FileStorage = require('../services/FileStorage');
/* POST /subscribe */
router.post('/subscribe', async function (req, res) {
try {
if (!req.body || !req.body.email) {
return res.status(400).json({ error: "Wrong payload" });
}
if (req.body.email === 'forbidden#gmail.com') {
return res.status(422).json({ error: "Email is already in use" });
}
const data = {email: req.body.email};
await FileStorage.writeFile('user.json', data);
await res.json({success: true})
} catch (e) {
console.log(e);
res.status(500).send('Internal error');
}
});
/* GET /unsubscribe */
router.post('/unsubscribe ', async function (req, res) {
try {
await FileStorage.deleteFile('user.json');
await FileStorage.writeFile('user-analytics.json', []);
await FileStorage.writeFile('performance-analytics.json', []);
await res.json({success: true})
} catch (e) {
console.log(e);
res.status(500).send('Internal error');
}
});
module.exports = router;
And user.json file looks like this :
{"email":"Email#gmail.com"}
This is my attempt for unsubscribing :
export const unsubscribeUser = () => {
try {
const response = fetch('http://localhost:8080/unsubscribe', {
method: "POST"
});
if (!response.ok) {
const message = 'Error with Status Code: ' + response.status;
throw new Error(message);
}
const data = response.json();
console.log(data);
} catch (error) {
console.log('Error: ' + error);
}
}
It gives the following errors:
Error: Error: Error with Status Code: undefined
main.js:2
main.js:2 POST http://localhost:8080/unsubscribe 404 (Not Found)
FileStorage.js:
const fs = require('fs');
const fsp = fs.promises;
class FileStorage {
static getRealPath(path) {
return `${global.appRoot}/storage/${path}`
}
static async checkFileExist(path, mode = fs.constants.F_OK) {
try {
await fsp.access(FileStorage.getRealPath(path), mode);
return true
} catch (e) {
return false
}
}
static async readFile(path) {
if (await FileStorage.checkFileExist(path)) {
return await fsp.readFile(FileStorage.getRealPath(path), 'utf-8');
} else {
throw new Error('File read error');
}
}
static async readJsonFile(path) {
const rawJson = await FileStorage.readFile(path);
try {
return JSON.parse(rawJson);
} catch (e) {
return {error: 'Non valid JSON in file content'};
}
}
static async writeFile(path, content) {
const preparedContent = typeof content !== 'string' && typeof content === 'object' ? JSON.stringify(content) : content;
return await fsp.writeFile(FileStorage.getRealPath(path), preparedContent);
}
static async deleteFile(path) {
if (!await FileStorage.checkFileExist(path, fs.constants.F_OK | fs.constants.W_OK)) {
return await fsp.unlink(FileStorage.getRealPath(path));
}
return true;
}
}
module.exports = FileStorage;
You should consider using a database for handling CRUD operations on your persisted data. If you must use filestorage, theres a flat file DB library called lowdb that can make working the files easier.
As for preventing duplicate requests, you can track if user has already made a request.
let fetchBtn = document.getElementById('fetch')
let isFetching = false
fetchBtn.addEventListener('click', handleClick)
async function handleClick(){
if (isFetching) return // do nothing if request already made
isFetching = true
disableBtn()
const response = await fetchMock()
isFetching = false
enableBtn()
}
function fetchMock(){
// const response = await fetch("https://example.com");
return new Promise(resolve => setTimeout (() => resolve('hello'), 2000))
}
function disableBtn(){
fetchBtn.setAttribute('disabled', 'disabled');
fetchBtn.style.opacity = "0.5"
}
function enableBtn(){
fetchBtn.removeAttribute('disabled');
fetchBtn.style.opacity = "1"
}
<button type="button" id="fetch">Fetch</button>

Categories

Resources