Provisional headers are shown - node.js

I am using Extjs in web and node.js in the api side. I called the api defined, from the web. I passed params and required data as request, but its showing the below error and request is unsuccessful.
Here is the api call code:
Ext.Ajax.request({
url: "http://localhost:3000/update-fund",
method: "POST",
dataType: 'json',
params: {
userId: userDocGlobal.id
},
headers: {
'Content-Type': 'application/json'
},
jsonData: {
fundId: PECalculator.selectedFund,
fundDate: getAiqDateFromPicker(Ext.getCmp("currentCalculationDateFundLevel")),
fundData: fund,
ownerId: userDocGlobal.companyid,
lpId: userDocGlobal.companyid,
role: userDocGlobal.role,
userId: userDocGlobal.id,
companyid: userDocGlobal.companyid
},
success: function (response) {
if (callback) {
callback(response);
}
if(userRole === "FREE"){
moduleObj.setFundNameAndCalcDateForFreeUser();
}
},
error: function () {
if (errorCallback) {
errorCallback();
}
}
})

Related

Why is there no other successful status codes in fastify route?

So I created a fastify route using fastify.route. But there is no way I could return a 201 statusCode in the response. And even if I return a 201 statusCode, it will be converted to a 200 one.
fastify.route({
method: 'GET',
url: '/',
schema: {
querystring: {
name: { type: 'string' },
excitement: { type: 'integer' }
},
response: {
200: {
type: 'object',
properties: {
hello: { type: 'string' }
}
}
}
},
handler: function (request, reply) {
reply.send({ hello: 'world' })
}
})
ΒΆ
EDIT
The code that I was referring to was that of swagger
response: {
200: {
type: 'object',
properties: {
hello: { type: 'string' }
}
}
}
Here I want to replace 200 with a 201, and gives the required fields, but seems like that is not throwing an error as imagined
This is messing up my post request.

How to send react native text field value as JSON.stringify

I have code like this:-
export default class TextField extends Component {
constructor(props) {
super(props);
this.state = {
userID: '',
userName: '',
userGmail: '',
userTNumber: '',
};
}
addCustomer = () => {
fetch('http://localhost:3000/send-data', {
method: 'post',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({}),
});
} <TextInput
style={styles.inputText}
placeholder="User ID :"
placeholderTextColor="#ffff"
onChangeText={userID => this.setState({userID})}
value={this.state.userID}
autoCapitalize="none"
/>
</View>
}
I Need To Send My Text Input To My Node BackEnd...
I Don't Know How To Send My Data Using This Fetch Function
**
addCustomer = () => {
fetch('http://localhost:3000/send-data', {
method: 'post',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({}),
});
};
**
I Don't Know How To Put My Text Input Into,
body: JSON.stringify({}),
This Is My BackEnd To Post My Data:-
app.post('/send-data', (req, res) => {
const customer = new Customer({
userID: req.body.userID,
userName: req.body.userName,
userGmail: req.body.userGmail,
userTNumber: req.body.userTNumber,
});
customer
.save()
.then(result => {
console.log(result);
res.send(result);
})
.catch(err => {
console.log(err);
});
});
Can You Help Me ..?
ThankYou..!
If I understood correctly, you want to pass your data in the following format:
{
"userID": 1,
"userName": "John Doe",
"userGmail": "john.doe#example.com",
"userTNumber": "1234"
}
You want to use the data from your state and pass it to the fetch function, like so:
export default class TextField extends Component {
constructor(props) {
super(props)
this.state = {
userID: "",
userName: "",
userGmail: "",
userTNumber: "",
}
}
addCustomer = () => {
const { userID, userName, userGmail, userTNumber } = this.state
fetch("http://localhost:3000/send-data", {
method: "post",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ userID, userName, userGmail, userTNumber }),
})
}
render() {
return (
<TextInput
style={styles.inputText}
placeholder="User ID :"
placeholderTextColor="#ffff"
onChangeText={(userID) => this.setState({ userID })}
value={this.state.userID}
autoCapitalize="none"
/>
)
}
}

Returning responses from got (requests) to an object for callback

I am using got module to make POST requests to get data.
I am wanting to synchronously call 3 APIs, get the response objects, then callback. I am having trouble getting returning the response to callback object. It is returning {} instead of the actual response. I would also like to make all of these calls synchronously so that the requests are occurring simultaneously to save time.
const got = require('got');
exports.handler = (event, context, callback) => {
async function getDATA1() {
return await got.post('https://url.com/serviceapi/1/', {
responseType: 'json',
resolveBodyOnly: true,
username: 'user',
password: 'pass',
json: {
"Input": {
"item":1,
}
}
}).json();
}
async function getDATA2() {
return await got.post('https://url.com/serviceapi/2/', {
responseType: 'json',
resolveBodyOnly: true,
username: 'user',
password: 'pass',
json: {
"Input": {
"item":2,
"color":"blue",
}
}
}).json();
}
async function getDATA3() {
return await got.post('https://url.com/serviceapi/3/', {
responseType: 'json',
resolveBodyOnly: true,
username: 'user',
password: 'pass',
json: {
"Input": {
"item":3,
"size":"large",
}
}
}).json();
}
callback(null,{
"DATA1": getDATA1(),
"DATA2": getDATA2(),
"DATA3": getDATA3(),
});
};
The response I am getting is
{
"DATA1": {},
"DATA2": {},
"DATA3": {}
}
The response I am expected/ want is something like this
{
"DATA1": {
"available_f":"Y"
},
"DATA2": {
"available_f":"N"
},
"DATA3": {
"available_f":"Y"
},
}
Those async functions will need to be awaited so you would need to do something like this that will wait till all of the requests have resolved and then you can gather the results and return them through the callback.
const got = require('got');
exports.handler = (event, context, callback) => {
async function getDATA1() {
return await got.post('https://url.com/serviceapi/1/', {
responseType: 'json',
resolveBodyOnly: true,
username: 'user',
password: 'pass',
json: {
"Input": {
"item": 1,
}
}
}).json();
}
async function getDATA2() {
return await got.post('https://url.com/serviceapi/2/', {
responseType: 'json',
resolveBodyOnly: true,
username: 'user',
password: 'pass',
json: {
"Input": {
"item": 2,
"color": "blue",
}
}
}).json();
}
async function getDATA3() {
return await got.post('https://url.com/serviceapi/3/', {
responseType: 'json',
resolveBodyOnly: true,
username: 'user',
password: 'pass',
json: {
"Input": {
"item": 3,
"size": "large",
}
}
}).json();
}
Promise.all([getDATA1, getDATA2, getDATA3]).then(values => {
return callback(null, {
DATA1: values[0],
DATA2: values[1],
DATA3: values[2]
})
}).catch(err => {
return callback(err);
});
};

using request-promise to querystring in JSON

I have a big API I want to query for userId and receive its details.
var options = {
uri: 'http://www.theapi.net/0862710324bo0',
method : 'GET',
useQuerystring: true,
qs: {
"must": [
{ "match": { "data.clients.id": req.params.userId }},
]
},
headers: {
'User-Agent': 'Request-Promise'
},
json: true // Automatically parses the JSON string in the response
};
console.log(options.qs.must)
rp(options)
.then(function (repos) {
console.log(repos.clients.name);
res.status(200).json({
data:repos.clients[0].name
})
})...
This code returns:
[
{
match: { 'data.clients.id': 'b2d445-2160-4va7-ref-4edf860bd' }
}
]
undefined (because I didn't specify the object array index)
{
"data": "Sergio"
}
What I need:
{
"id":"ec9c1c4d-ab1a-41b2-bc1a-520b889cdeb9",
"name":"Sergio",
"email":"sergio#jorge.com",
},
I believe adding a "bool" tag would help you out.
var options = {
uri: 'http://www.theapi.net/0862710324bo0',
method : 'GET',
useQuerystring: true,
qs: {
"bool": { // Tag added
"must": [
{ "match": { "data.clients.id": req.params.userId }},
]
}
}
headers: {
'User-Agent': 'Request-Promise'
},
json: true // Automatically parses the JSON string in the response
};
console.log(options.qs.must)
rp(options)
.then(function (repos) {
console.log(repos.clients.name);
res.status(200).json({
data:repos.clients[0].name
})
})
Beware - Untested code!
for (const [key, value] of Object.entries(repos.clients)) {
if (req.params.userId === repos.clients[key].id) {
return res.status(200).json({
data:repos.clients[key]
})
}
}

Node update not working, format is wrong while send to api

I try to update my data from Angular to Node.js
component.ts
updatefunction(id,data){
console.log("component",data);
//component {role: "User", _id: "5c2dc052d6bfba36b41b34dd", name: "Test", email: "test123#gmail.com", //username: "Test"}
this.uAdminService
.updateUser(id,data).subscribe(
result => {
//console.log(result.json());
},
error => {
console.log(error.json());
}
);
}
in myservice.ts
updatefunction(id, data){
console.log("service", data);
//service {role: "User", _id: "5c2dc052d6bfba36b41b34dd", name: "Test", email: "test123#gmail.com", //username: "Test"}
let headers = new Headers({ 'x-access-token': this.token, 'Content-Type': 'application/x-www-form-urlencoded' });
let options = new RequestOptions({ headers: headers });
return this.http.put(this.url+id, data, options);
}
my nodejs controller
router.put('/:id', VerifyToken, function (req, res) {
console.log(req.body);
//{'{\n "role": "User", \n "_id": "5c2dc052d6bfba36b41b34dd" \n}'}
User.findByIdAndUpdate({_id:req.params.id}, req.body, {new: true}).select("-password")
.then(users => {
res.send(users);
}).catch(err => {
res.status(500).send({
message: err.message || "Some error occurred while retrieving Report."
});
});
});
my req.body console like this {'{\n "role": "User", \n "_id": "5c2dc052d6bfba36b41b34dd" \n}'} but i pass from angularjs in this format {role: "User", _id: "5c2dc052d6bfba36b41b34dd", name: "Test", email: "test123#gmail.com", //username: "Test"}
I don't know why it's converting so that it's not update to db
if i console from api it will like this { name: "Test",email: "test123#gmail.com"}
Update myservice.ts like below:
updatefunction(id, data){
console.log("service", data);
//service {role: "User", _id: "5c2dc052d6bfba36b41b34dd", name: "Test", email: "test123#gmail.com", //username: "Test"}
let headers = new Headers({ 'x-access-token': this.token, 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.put(this.url+id, data, options);
}
Changed the Content-Type to application/json as you are sending a json formatted data and not form data.

Resources