Method: 'GET' how should I do to get my search bar work? - get

Hi guy how should i modified the code to get my search bar actually work? currently my search bar not work correctly.
This is the result of my project
async onSearch_new(value){
console.log(value);
const {taoBao} = this.state
const url = 'http://rap2api.taobao.org/app/mock/250089/testCompanies'
const response = await fetch(url, {
method: 'GET',//GET,POST,PUT,DELETE,ETC.
mode: 'cors',//no-cors, cors, same-origin
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json'
},
redirect: 'follow',
referrerPolicy: 'no-referrer',
//body: JSON.stringify({
// company: value.company
//})
});
response.json().then((data) => {
console.log(data);
if (data && data.code == 0) {
this.setState({
taoBao: taoBao
})
}
else {
Next.Notification.error({
title: 'Fail',
style: {
width: 600,
marginLeft: -255
}
});
}
})

Related

fetch request is called twice?

After checking other posts, I did not find an exact answer to my question but apparently this problem happens to others, just not exactly my problem.
Every PUT, POST , DELETE Request sent from the function below is called twice.
HERE is my function code that handle user changes(add,update,delete) to the UI.
it's part of ReactJS class component
commitChanges({ added, changed, deleted }) {
this.setState((state) => {
let { data } = state;
if (added) {
const startingAddedId = data!=undefined && data.length > 0 ? data[data.length - 1].id + 1 : 0;
var TBname= decodeURIComponent(window.location.pathname.slice(window.location.pathname.lastIndexOf(':')+1 ));
if ( data == undefined) data = [{ id: startingAddedId, ...added} ];
data = [...data, { id: startingAddedId, ...added }];
fetch('http://localhost:3001/api/appo',
{
method: 'POST',
headers: { 'Accept': 'application/json, text/plain, */*' ,'Content-Type': 'application/json' },
body: JSON.stringify({ id: startingAddedId,"TBname": TBname, ...added } )
})
.then( (response) => this.setState({ data: data }) ) .catch(() => console.log('POST failed'));
this.setState({ data: data })
console.log(this.state.data);
}
if (changed) {
data.map((appointment) => {
console.log(changed[appointment._id]);
if (changed[appointment.id] != undefined) {
//console.log("JSON",JSON.stringify({...appointment,...changed[appointment.id],} ) );
fetch('http://localhost:3001/api/appo/'+appointment.id,
{
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({...appointment,...changed[appointment.id],} )
}).catch(() => console.log('PUT failed'));
}
});
data = data.map((appointment) =>
changed[appointment.id] ? { ...appointment, ...changed[appointment.id] } : appointment)
this.setState({ data: data });
}
if (deleted !== undefined) {
console.log(deleted);
fetch('http://localhost:3001/api/appo/'+deleted,
{
method: 'DELETE',
headers: { 'Content-Type': 'application/json' },
}).catch(() => console.log('DELETE failed'));
data = data.filter(appointment => appointment.id !== deleted);
this.setState({ data: data })
}
return { data };
});
}
For example if I want to send POST Request to create an item this item will be created twice with the same id .
Double POST REQUEST
Don't make any http request inside the setState callback function, its not a good practise and setting a state inside the state callback result this issue.
remove the setState callback and doing something like below will resolve your issue.
commitChanges({ added, changed, deleted }) {
let { data } = state;
if (added) {
const startingAddedId = data!=undefined && data.length > 0 ? data[data.length - 1].id + 1 : 0;
var TBname= decodeURIComponent(window.location.pathname.slice(window.location.pathname.lastIndexOf(':')+1 ));
if ( data == undefined) data = [{ id: startingAddedId, ...added} ];
data = [...data, { id: startingAddedId, ...added }];
fetch('http://localhost:3001/api/appo',
{
method: 'POST',
headers: { 'Accept': 'application/json, text/plain, */*' ,'Content-Type': 'application/json' },
body: JSON.stringify({ id: startingAddedId,"TBname": TBname, ...added } )
})
.then( (response) => this.setState({ data: data }) ) .catch(() => console.log('POST failed'));
this.setState({ data: data })
console.log(this.state.data);
}
if (changed) {
data.map((appointment) => {
console.log(changed[appointment._id]);
if (changed[appointment.id] != undefined) {
//console.log("JSON",JSON.stringify({...appointment,...changed[appointment.id],} ) );
fetch('http://localhost:3001/api/appo/'+appointment.id,
{
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({...appointment,...changed[appointment.id],} )
}).catch(() => console.log('PUT failed'));
}
});
data = data.map((appointment) =>
changed[appointment.id] ? { ...appointment, ...changed[appointment.id] } : appointment)
this.setState({ data: data });
}
if (deleted !== undefined) {
console.log(deleted);
fetch('http://localhost:3001/api/appo/'+deleted,
{
method: 'DELETE',
headers: { 'Content-Type': 'application/json' },
}).catch(() => console.log('DELETE failed'));
data = data.filter(appointment => appointment.id !== deleted);
this.setState({ data: data })
}
}

API call works with Postman, but does not with Axios

I am using third party API. The way it works is:
I send post request then Token is returned in response.
Then i use that Token to check status. Afterwards, report is returned in response
In postman, i make both calls separately and it is working, but in Axios I have 1 async function and 2 await Promises.
Postman(NodeJs - Axios) looks like this:
For getting Token:
var data = JSON.stringify({
"security": {
"pLogin": "a",
"pPassword": "io"
},
"data": {
"pHead": "005",
"pCode": "00433",
"pLegal": 1,
"pClaimId": "z4LpXRWZKecSnL-FQtgD",
"pReportId": 8,
"pReportFormat": 1
}
});
var config = {
method: 'post',
url: 'http://10.22.50.10/report/',
headers: {
'Content-Type': 'application/json'
},
data : data
};
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
For getting Report with the token:
var data = JSON.stringify({
"data": {
"pHead": "005",
"pCode": "00433",
"pToken": "kgqjismxdrpjnjaqnlnbmovcsvnkarfd",
"pClaimId": "z4LpXRWZKecSnL-FQtgD",
"pReportFormat": 1
}
});
var config = {
method: 'post',
url: 'http://10.22.50.10/report/status',
headers: {
'Content-Type': 'application/json'
},
data : data
};
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
My async function with Axios:
/* 1. Searching for client in database (Full name is used, but can be changed)*/
const client = await client.findOne({
name: body.name,
family_name: body.family_name,
patronymic: body.patronymic
});
if (!client) {
return res.status(401).json({ message: "Client is not registered" });
}
/* 2. If client was found in database, make an API call */
let credit_report;
try{
credit_report = await axios.post(
'http://10.22.50.10/report',
{
security: {
pLogin: 'a',
pPassword: 'io',
},
data: {
pHead: "005",
pCode: "00433",
pLegal: 1,
pClaimId: client.claim_id,
pReportId: 8,
pReportFormat: 1
}
},
{
headers: {
'content-type': 'application/json'
}
}
);
}catch(err){
return res.status(400).json({errorMessage: err.message})
}
// await new Promise(resolve => setTimeout(resolve, 3000));
if(!credit_report.data.data.token) return res.status(400).json({message: credit_report.data});
const credit_report_status = await axios.post(
'http://10.22.50.10/report/status',
{
data: {
pHead: "005",
pCode: "00433",
pToken: credit_report.data.data.token,
pClaimId: client.claim_id,
pReportFormat: 1
}
},
{
headers: {
'content-type': 'application/json'
}
}
);
console.log(credit_report_status)
if(credit_report_status.data.data.result == '05000') return res.status(200).json({ message: 'Client fetched.', clientData64: credit_report_status.data.data.reportBase64});
else return res.status(400).json({message: credit_report_status.data})
When I am using Postman to check my module, it is saying Error 400 Bad Request

Unable to use a async method on button action in js file

I am new to react development
I have a js file in a react app, which has a button
<CardFooter className="text-center">
block
className="btn-round"
color="info"
href="#pablo"
onClick= "handleVerify()"
size="lg"
I am getting warning as handleverify is defined but never used
async function handleVerify(){
// e.preventDefault();
const response = await fetch('/api/emailVerifier', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ post: this.state.post }),
});
const body = await response.text();
this.setState({ responseToPost: body });
};
Your onClick should looks like this:
onClick={() => handleVerify()}
In componentDidMount you can make something like this
async function handleVerify(){
// e.preventDefault();
const response = await fetch('/api/emailVerifier', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ post: this.state.post }),
});
return await response.text();
}
componentDidMount() {
handleVerify().then(body=> {
this.setState({ responseToPost: });
})
}

digisigner document api gives Bad Request error if I call it with axios

DigiSigner is working fine if I call it from the postman, but it is giving error Bad Request if I call it with axios form nodejs application.
Here is my code sample.
const digi_signer_url = "https://api.digisigner.com/v1/documents";
const digi_signer_options = {
method: 'POST',
headers: { "Content-Type": "multipart/form-data", 'Authorization': `Basic ${process.env.DIGI_SIGNER_KEY}` },
data: {file: file},
url: digi_signer_url,
}
const r = axios(digi_signer_options)
Here is the solution.
const opts = {
method: 'POST',
url: 'https://api.digisigner.com/v1/documents',
headers:
{
'cache-control': 'no-cache',
authorization: `Basic ${process.env.DIGI_SIGNER_KEY}`,
'content-type': 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW'
},
formData:
{
file:
{
value: fs.createReadStream(path.join(__dirname, '../../templates/sample-po.pdf')),
options: { filename: 'sample-po.pdf', contentType: null }
}
}
};
request(opts, function (error, response, body) {
if (error) throw new Error(error);
if (body) {
const document = JSON.parse(body);
const {document_id} = document;
const send_to_signature = {
method: 'POST',
url: 'https://api.digisigner.com/v1/signature_requests',
headers:
{
'cache-control': 'no-cache',
'content-type': 'application/json',
authorization: `Basic ${process.env.DIGI_SIGNER_KEY}`
},
body:
{
documents:
[{
document_id: document_id,
subject: subject,
message: content,
signers:
[{
email: to_email,
fields: [{ page: 0, rectangle: [0, 0, 200, 100], type: 'SIGNATURE' }]
}]
}]
},
json: true
};
request(send_to_signature, function (error, response, result) {
if (error) throw new Error(error);
console.log(result)
});
}
});

Node JS request-promise for PUT with auth

I want to upload a file to server with request-promise.
var requestPromise = require('request-promise');
var options = {
uri: 'myurl.com/putImage/image.jpg',
method: 'PUT',
auth: {
'user': 'myusername',
'pass': 'mypassword',
'sendImmediately': false
},
multipart: [
{
'content-type': 'application/json',
body: JSON.stringify({foo: 'bar', _attachments: {'message.txt': {follows: true, length: 18, 'content_type': 'text/plain' }}})
},
{ body: 'I am an attachment' },
{ body: fs.createReadStream('test.jpg') }
]
};
The constroller function has:
requestPromise.put(options)
.then(function() {
response = {
statusCode: 200,
message: "Success",
};
log.info("Success");
res.status(200).send(response);
})
.catch(function (error) {
response = {
statusCode: error.status,
message: error.message
};
log.info(response);
res.status(400).send(response);
});
I never get to success nor catch an error. What must be wrong? Actual work to be done is a curl like this:
curl --verbose -u myusername:mypassword -X PUT --upload-file test.jpg myurl.com/putImage/image.jpg
What is the best approach for this? Can request-promise do this?
Got it to upload with change in options:
var options = {
uri: 'myurl.com/putImage/image.jpg',
method: 'PUT',
auth: {
'user': 'myusername',
'pass': 'mypassword'
},
multipart: [
{ body: fs.createReadStream('test.jpg') }
]
};
Is there any better approach?

Resources