I'm building a webapplication in NodeJS.
Back-end in application is connected with user just via Json API. I'm trying to do login option. It's possible? How can I receive response from Passport Authenticate?
function post_api(req, res) {
res.writeHead(200, { 'Content-Type': 'application/json' });
// Check method
if(!req.body.method)
res.write( JSON.stringify({
"status":"400",
"response": {
"status" : "error",
"info": "Method not defined."
}
}));
else
{
if(req.body.method == "login")
{
passport.authenticate('local', {failureFlash: true, successFlash: true});
// Something here but i have no idea what...
res.write( JSON.stringify({
"status":"200",
"response": {
"status" : "error", // or success
"info": req.flash('error')
}
}));
}
else
res.write( JSON.stringify({
"status":"404",
"response": {
"status" : "error",
"info": "Method not found."
}
}));
}
res.end(); };
This of course doesn't works, how it should look like?
Related
I am trying to make a Post request to an api but for some reason i am getting a 400 feedback in the process. Being that i am a beginner at this, i can't really figure out where i am getting it wrong. I understand 400 error has to do with incorrect syntax but i am not sure that is the case here. I also checked out the other related posts but none helped address my problem. I have also read through the documentation over and over again but still can't see where i am making a mistake. I will appreciate if you helped me point out the problem.
myPostRequest(){
var mybody = {
"amount": "5.0",
"currency": "EUR",
"externalId": "6547864",
"payer": { "partyIdType": "MSISDN","partyId": "0977948551"}
}
mybody = JSON.stringify(mybody);
var token = "mytoken";
//POST request
fetch('https://sandbox.momodeveloper.mtn.com/collection/v1_0/requesttopay', {
method: "POST",
headers: {
'Authorization': 'Bearer '+token,
'X-Reference-Id': 'f9b8b0a-XXXXXXXXXX',
'X-Target-Environment': 'sandbox',
'Ocp-Apim-Subscription-Key': '14d2a71dXXXXXXXXX',
},
body: mybody,
})
.then((responseJson) => {
alert(JSON.stringify(responseJson));
console.log(responseJson);
})
.catch((error) => {
alert(JSON.stringify(error));
console.error(error);
});
}
Use axios/apisauce instead of fetch
apisauce example:
import { create } from 'apisauce';
const api = create({
baseURL: `http://example.com`,
});
const response = await api.post('/path/to/', body, { headers });
In your case:
import { create } from 'apisauce';
const api = create({
baseURL: `https://sandbox.momodeveloper.mtn.com`,
});
const response = await api.post(
'/collection/v1_0/requesttopay',
{
"amount": "5.0",
"currency": "EUR",
"externalId": "6547864",
"payer": { "partyIdType": "MSISDN", "partyId": "0977948551" }
},
{
headers: {
'Authorization': 'Bearer ' + token,
'X-Reference-Id': 'f9b8b0a-XXXXXXXXXX',
'X-Target-Environment': 'sandbox',
'Ocp-Apim-Subscription-Key': '14d2a71dXXXXXXXXX',
}
}
);
If I do this in PostMan, I get a response back which I can toggle html and json, but in my react native app I'm getting a console error of JSON Parse Error: Unexpected EOF
I have the content type of my sent header as x-www-form-urlencoded because that was the only way to get my proper response even on postman.
I have my backend in wordpress sending a response array as json_encoded (echo json_encode($response)) and I can get it by url and post man, but my app just can't get past this unexpected EOF and I think it has to do with my .then statements
WHat am I doing wrong here?
validate(){
const {navigate} = this.props.navigation;
this.setState({ validating: true });
let formData = new FormData();
formData.append('type', 'login');
formData.append('email', this.state.email);
formData.append('password', this.state.password);
return fetch('https:/site/authentication.php', {
method: 'POST',
body: JSON.stringify(formData),
headers:{
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.then(response => response.json())
.then(data => {
console.log(data);
return data;
})
.catch(function(err) {
console.log(err);
})
}
Looking at your response:
Response { "_bodyBlob": Blob { "_data": Object { "blobId": "31418cda-5d2e-4ee0-8c67-626e7ebe0502", "offset": 0, "size": 0, }, }, "headers": Headers { "map": Object { "cache-control": "public, max-age=0", "content-length": "0", "content-type": "text/html; charset=UTF-8", }, }, "ok": true, "status": 200, "statusText": undefined, "type": "default", "url": "https://site/authentication.php", } Promise { "_40": 0, "_55": null, "_65": 0, "_72": null, }
I think it is a blob not JSON. Try and use this instead:
.then(response => response.blob())
Sorry I missed that earlier.
Blob MDN Ref: response.blob()
Hello I want to put operation in a JSON format . Probably My JSON parse error so that I can't able to update Data . My JSON body data is
[{
"receiptNo": "21456",
"rollno": 12201,
"bankcode": 2,
"userid": "rifat",
"__v": "0"
}]
And my NodeJS code :
router.put('/receiptmaster1/update/:receiptNo', function (req,res) {
receipt_master1.updateMany({
receiptNo: req.params.receiptNo
}, {
receiptNo: req.body.receiptNo,
rollno: req.body.rollno,
bankcode : req.body.bankcode,
userid: 'rifat',
__v: "0"
}).then(function(err) {
res.send({
success: true,
message: "Updated Successfully Master2"
});
}).catch(err => {
res.status(500).send({
message: err.message || "Error while Updating Server Data"
});
});
});
My data is not updated though I have got this response
"success":true,"message":"Updated Successfully Master2"
Please Help.
Your JSON is a single object in an array. Either change the posted format to be an object (without the wrapping array) when you send it:
{
"receiptNo": "21456",
"rollno": 12201,
"bankcode": 2,
"userid": "rifat",
"__v": "0"
}
or change how you access it on the server:
router.put('/receiptmaster1/update/:receiptNo', function (req,res) {
receipt_master1.updateMany({
receiptNo: req.params.receiptNo
}, {
receiptNo: req.body[0].receiptNo,
rollno: req.body[0].rollno,
bankcode : req.body[0].bankcode,
userid: 'rifat',
__v: "0"
}).then(function(err) {
res.send({
success: true,
message: "Updated Successfully Master2"
});
}).catch(err => {
res.status(500).send({
message: err.message || "Error while Updating Server Data"
});
});
});
Note the change from req.body. to req.body[0].
I'm getting a serialized JSON body from our API like the below example: '
{
"_embedded": [
{
"id": 1,
"vulnerable": false,
"systemId": "something",
"friendlyName": "a friendly name"
},
]
}
How to show just the key/value friendlyName? I'm using axios to get the response. This is my code:
axios.get(BASE_URL + 'household/list',{
headers: { Authorization: AuthStr },
transformResponse: axios.defaults.transformResponse.concat((data) => {
console.log(data) // this should now be JSON
})
}).then(({ data })=> {
this.setState({
data: houses.friendlyName
});
})
.catch((err)=> {
console.log(err);
});
I think I'm supposed to transform the data, but I don't know how. Thanks for any help.
Edit: This is how the response is shown in console:
_embedded:
0:
friendlyName: "a friendly name"
id: 1
systemId: "GE8BP2IACH7"
vulnerable: false
So, how do I deserialize it?
axios.get(BASE_URL + 'household/list',{
headers: { Authorization: AuthStr },
}).then(function (response) {
this.setState({data:response._embedded.friendlyName})
})
.catch(function (error) {
console.log(error);
});
I am trying to call GCM notification by using POST.
The code I am using is :
var jsonbody={"to": "/topics/global",
"data": {
"title": "TestTitle",
"is_background": false,
"message": "Testmessage",
"image": "",
"payload": {
"team": "India",
"score": "5.6" },
"timestamp": "2016-12-13 16:32:05"
}
};
var request = require('request');
request.post({
headers: {'content-type': 'application/json',
Authorization:'key=(my key)'},
url: 'https://fcm.googleapis.com/fcm/send',
BODY: jsonbody
}, function (error, response, body) {
if (error) {
console.log('failure ' + error);
} else {
console.log('success '+response + 'and ' +body);
}
});
I am getting error as :
success [object Object]and JSON_PARSING_ERROR: Unexpected token END
OF FILE at position 0.
I was actually missing something :
body: JSON.stringify(jsonbody)
Rest all was correct.