const fetch = require('node-fetch');
const FormData = require('form-data');
async function check () {
const form = new FormData();
form.append('merchantIdentifier', 'b19e8f103bce406cbd3476431b6b7973')
form.append('orderId', 'ZPK12345' )
form.append('mode', 0)
form.append('checksum', '94681259256bc24e3c6881fe85e0fd61cf1b41a0e650c9ca6b7b7fe7ae510af4')
try {
const result = await fetch(`http://zaakpaystaging.centralindia.cloudapp.azure.com:8080/checktransaction?v=5`, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: form
})
const data = await result.text()
console.log(data)
} catch (error) {
console.log(error);
}
}
check()
sending data to http://zaakpaystaging.centralindia.cloudapp.azure.com:8080/checktransaction?v=5 through form data but response form value is null
Related
so I have a simple express/node with a vanillah js front-end.
Here is what my post request looks like:
const postContent = document.querySelector('#post-content');
const postButton = document.querySelector('#post-button');
const img = document.querySelector('#img');
const formData = new FormData();
postButton.addEventListener("click", function(e) {
e.preventDefault();
let data = {
body: postContent.value,
comments: [],
reactionEmoji: [{
"type": "๐",
"count": 0
},
{
"type": "๐ฅ",
"count": 0
},
{
"type": "๐ฎ",
"count": 0
}]
}
let imgData = img.files[0]
console.log(imgData)
formData.append("photo", imgData);
formData.append("data", JSON.stringify(data));
console.log(formData.get("photo"))
sendPost(formData)
});
const sendPost = (input) => {
//console.log(input.get("photo"))
let url = `http://localhost:3000/posts`
let obj = {
method: 'POST',
headers: {
'Accept': 'application/json',
},
body: input
}
return new Promise(async (res, rej) => {
try {
const response = await fetch(url, obj);
const data = await response.json();
res(data)
} catch (err) {
console.log(err)
rej(`${err}`)
}
})
}
Now because i am sending a multipart/form-data, i have to json parse the req.body.data
which looks like this on the server-side
console.log('req.file')
console.log(req.file)
let postToAdd = JSON.parse(req.body.data);
postToAdd = req.body.data
If I were to send just json with content type of application/json, express was parsing for me with express.json but now I have to JSON.parse.
Is this the right way to do it?
Hi i'm using MeaningCloud's api to get the proper object back once it analyses a string of text or a url for the Natural language processing (NLP). But it doesn't return the proper object.
Right now the code returns a string with the text "[Object object]" on the HTML page. I need it to return the results of the api call which returns the proper JSON object(that I can see in the console) in a proper "key/value" pair format on the HTML page.
Here's my script:
const baseURL = "https://api.meaningcloud.com/sentiment-2.1";
const key = "Your_api_key";
const submitBtn = document.getElementById("submitBtn");
submitBtn.addEventListener("click", (e) => {
e.preventDefault();
const url = document.getElementById("url").value;
if (url !== "") {
getData(baseURL, url, key)
.then(function (data) {
postData("/add", { data: data });
}).then(function () {
receiveData()
}).catch(function (error) {
console.log(error);
alert("Invalid input");
})
}
})
const getData = async (baseURL, url, key) => {
const res = await fetch(`${baseURL}?key=${key}&txt=${url}`)
try {
const data = await res.json();
return data;
}
catch (error) {
console.log("error", error);
}
}
const postData = async (url = "", data = {}) => {
const response = await fetch(url, {
method: "POST",
credentials: "same-origin",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
data: data
})
});
try {
const newData = await response.json();
return newData;
} catch (error) {
console.log(error);
}
};
const receiveData = async () => {
const request = await fetch('/all');
try {
// Transform into JSON
const allData = await request.json()
console.log(allData)
// Write updated data to DOM elements
document.getElementById('result').innerHTML = allData;
}
catch (error) {
console.log("error", error);
// appropriately handle the error
}
}
I have another main file that's the server.js file which I run using node server.js that renders the html page properly but the script doesn't render the results on the page properly. You can signup on meaningcloud for a free api key that has a very convenient number of calls you can make.
I need to have number format passed to JSON and I cannot use input type hidden because it returns string. I have const formDataJsonString = JSON.stringify(plainFormData); to translate form data to JSON (see below)
How do I POST javascript variable from form into JSON with the functions that I added below?
I have written this to convert it into number but have no clue on how to submit the javascript variable to JSON.
<input type="hidden" class="number" name="applicationType" value=3>
$("#form").submit(function(){
var formInfo = document.forms['form'];
var applicationType = parseInt($(".number").val());
});
The desired result in JSON:
applicationType: 3
Instead of:
applicationType: "3"
UPDATE 1:
So I have this to make it into JSON, and then POST it:
//url is the api
async function postFormDataAsJson({ url, formData }) {
const plainFormData = Object.fromEntries(formData.entries());
//put all accountsToLink value into an array
plainFormData["accountsToLink"] = new Array //create array
$("input[name=accountsToLink] ").each(function() {
plainFormData["accountsToLink"].push($(this).val()) //push value in array
});
const formDataJsonString = JSON.stringify(plainFormData);
const fetchOptions = {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
body: formDataJsonString,
};
const response = await fetch(url, fetchOptions);
if (!response.ok) {
const errorMessage = await response.text();
throw new Error(errorMessage);
}
else if (response.ok) {
window.location.href = "confirmation.html";
}
return response.json();
}
async function handleFormSubmit(event) {
event.preventDefault();
const form = event.currentTarget;
const url = form.action;
try {
const formData = new FormData(form);
const responseData = await postFormDataAsJson({ url, formData });
console.log({ responseData });
} catch (error) {
console.error(error);
}
}
const testform = document.getElementById('testform');
testform.addEventListener('submit', handleFormSubmit);
So you failed to mention you do NOT do what you did in the initial post but instead you use formData
You cannot use formData to JSON integers.
You can map a serialized array and stringify that
async function postFormDataAsJson({ url, formData }) {
const formDataJsonString = JSON.stringify(formData);
console.log(url,formDataJsonString)
// ....
}
async function handleFormSubmit(event) {
event.preventDefault();
const form = event.currentTarget;
const url = form.action;
try {
const formData = $(form).serializeArray().map(
item => ({ [item.name]: isNaN(item.value) ? item.value : +item.value})
);
const responseData = await postFormDataAsJson({ url, formData });
} catch (error) {
console.error(error);
}
}
$("#testform").on("submit", handleFormSubmit);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="testform" action="/bla.php">
<input type="hidden" class="number" name="applicationType" value=3>
<input type="submit" />
</form>
I have a form code that the api is a PUT method, I have a part where I have to send it in the form of a objects, but when I send it it sends it to me as an array, they also tell me that I have to send them if it is true or false
handleSubmit = async (event) => {
const {
state,
city,
mild_symptoms = [],
} = event
const YES = "Si"
console.log(event)
try {
const myHeaders = new Headers();
const url =
"XXXXXXXXX";
myHeaders.append(
"x-api-key",
"XXXXX"
);
myHeaders.append("state", state);
myHeaders.append("city", city);
myHeaders.append(
"mild_symptoms",
`{"flu_syndrome": ${mild_symptoms.includes("flu_syndrome")}, "conjunctivitis": ${mild_symptoms.includes("conjunctivitis")}, "muscle_pain": ${mild_symptoms.includes("muscle_pain")}}`
);
var requestOptions = {
method: "PUT",
headers: myHeaders,
mode: "cors"
};
const response = await fetch(url, requestOptions);
console.log("FIRST RESPONSE ", response);
const result = await response.text();
console.log("RESULT", result);
Modal.success({
title: "รxito",
content: "Datos enviados correctamente",
onOk: ()=>{
window.location.href = "https://covid19.gob.sv/orientaciones-tecnicas/"
}
})
} catch (error) {
console.log("ERROR", error);
}
I have to send this as a objects and not as an array
"mild_symptoms",
`{"flu_syndrome": ${mild_symptoms.includes("flu_syndrome")}, "conjunctivitis": ${mild_symptoms.includes("conjunctivitis")}, "muscle_pain": ${mild_symptoms.includes("muscle_pain")}}`
);
Hello after setup a simple async function with promise return i'd like to use then promise instead of try!
But is returning
await is a reserved word
for the second await in the function.
i've tried to place async return promise the data! but did not worked either
async infiniteNotification(page = 1) {
let page = this.state.page;
console.log("^^^^^", page);
let auth_token = await AsyncStorage.getItem(AUTH_TOKEN);
fetch(`/notifications?page=${page}`, {
method: "GET",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Access: auth_token
},
params: { page }
})
.then(data => data.json())
.then(data => {
var allData = this.state.notifications.concat(data.notifications);
this.setState({
notifications: allData,
page: this.state.page + 1,
});
let auth_token = await AsyncStorage.getItem(AUTH_TOKEN);
fetch("/notifications/mark_as_read", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Access: auth_token
},
body: JSON.stringify({
notification: {
read: true
}
})
}).then(response => {
this.props.changeNotifications();
});
})
.catch(err => {
console.log(err);
});
}
> await is a reserved word (100:25)
let auth_token = await AsyncStorage.getItem(AUTH_TOKEN);
^
fetch("/notifications/mark_as_read", {
You should refactor how you make your requests. I would have a common function to handle setting up the request and everything.
const makeRequest = async (url, options, auth_token) => {
try {
// Default options and request method
if (!options) options = {}
options.method = options.method || 'GET'
// always pass a body through, handle the payload here
if (options.body && (options.method === 'POST' || options.method === 'PUT')) {
options.body = JSON.stringify(options.body)
} else if (options.body) {
url = appendQueryString(url, options.body)
delete options.body
}
// setup headers
if (!options.headers) options.headers = {}
const headers = new Headers()
for(const key of Object.keys(options.headers)) {
headers.append(key, (options.headers as any)[key])
}
if (auth_token) {
headers.append('Access', auth_token)
}
headers.append('Accept', 'application/json')
headers.append('Content-Type', 'application/json')
options.headers = headers
const response = await fetch(url, options as any)
const json = await response.json()
if (!response.ok) {
throw json
}
return json
} catch (e) {
console.error(e)
throw e
}
}
appendQueryString is a little helper util to do the get qs params in the url
const appendQueryString = (urlPath, params) => {
const searchParams = new URLSearchParams()
for (const key of Object.keys(params)) {
searchParams.append(key, params[key])
}
return `${urlPath}?${searchParams.toString()}`
}
Now, to get to how you update your code, you'll notice things become less verbose and more extensive.
async infiniteNotification(page = 1) {
try {
let auth_token = await AsyncStorage.getItem(AUTH_TOKEN);
const data = await makeRequest(
`/notifications`,
{ body: { page } },
auth_token
)
var allData = this.state.notifications.concat(data.notifications);
this.setState({
notifications: allData,
page: this.state.page + 1,
});
const markedAsReadResponse = makeRequest(
"/notifications/mark_as_read",
{
method: "POST",
body: {
notification: { read: true }
},
auth_token
)
this.props.changeNotifications();
} catch (e) {
// TODO handle your errors
}
}