ionic rest http problems - ionic-framework

export class HttpService {
constructor(private http:HttpClient) {}
post(serviceName:string,date:any){
const data = {};
const headers= new HttpHeaders();
const option = { header: headers, widthCredintials:false };
const url = environment.apiUrl + serviceName;
return this.http.post(url, JSON.stringify(data),option);
}
}
error:No Overload matches this call option
please help me what can ı do ?

Check below example hope this working
post(serviceName:string,date:any){
const data = {};
const headers= new HttpHeaders();
const url = environment.apiUrl + serviceName;
return this.http.post(url, JSON.stringify(data),{ headers, withCredentials: false });
}

Related

How to code Multipart-form POST REQUEST using apollo-datasource-rest

I want to code the multipart-form POST REQUEST below using apollo-datasource-rest
My attempt to code this leads to a BAD REQUEST error
const { RESTDataSource } = require('apollo-datasource-rest');
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
class SalesforceApi extends RESTDataSource {
constructor() {
super();
this.initialize({});
this.getAccessToken()
.then((accessToken) => {
this.headers = {
Authorization: `Bearer ${accessToken}`,
};
});
}
async getAccessToken() {
console.log('Getting Salesforce access token');
try {
const response = await this.post(
'https://test.salesforce.com/services/oauth2/token',
{
username: 'FILTERED#FILTERED',
password: `${'FILTERED'}`,
grant_type: 'password',
client_id: 'FILTERED',
client_secret: 'FILTERED',
},
{
headers: {
'Content-Type': 'multipart/form-data',
},
},
);
const { accessToken } = response;
console.log(`ChangeGear sessionId: ${accessToken}`);
return accessToken;
} catch (error) {
console.log(`${error}`);
}
return 'No access token!!!';
}
module.exports = SalesforceApi;
[server:salesforce:local] POST https://test.salesforce.com/services/oauth2/token (343ms)
[server:salesforce:local] Error: 400: Bad Request
If memory serves correctly, form data is serialized slightly differently hence why the FormData interface exists. And the apollo-datasource-rest's this.post method is just a wrapper around fetch, so something like the below should work.
Instead of passing the body as a JSON object, try something like this
const formData = new FormData();
formData.append('username', 'FILTERED#FILTERED');
// ... more append lines for your data
const response = await this.post(
'https://test.salesforce.com/services/oauth2/token',
formData
{
headers: {
'Content-Type': 'multipart/form-data',
},
},
);

FetchError: invalid json response body at http://localhost:3000/api/products/6092ca3460fc67315178f2fa reason: Unexpected token < in JSON at position 0

I am trying to fetch data from MongoDB, but apparently, it gives an error
FetchError: invalid json response body at
http://localhost:3000/api/products/6092ca3460fc67315178f2fa reason: Unexpected token < in JSON at position 0
const defaultEndpoint = 'http://localhost:3000/api/products/';
export const getStaticPaths = async () => {
const res = await fetch(defaultEndpoint);
const data = await res.json();
const paths = data.map (product => {
return {
params: { id: product._id.toString() }
}
})
return {
paths,
fallback: false
}
}
export const getStaticProps = async (context) => {
const id = context.params.id;
const res = await fetch ('http://localhost:3000/api/products/' + id);
const data = await res.json ();
return {
props: {product: data}
}
}
const Details = ({product}) => {
return (
<div>
<h1>{product.title}</h1>
</div>
)
}
export default Details
API Endpoint which is perfectly working on http://localhost:3000/api/products
import { connectToDatabase } from "../../util/mongodb";
export default async (req, res) => {
const { db } = await connectToDatabase();
const products = await db.collection("products").find({}).toArray();
res.json(products);
};

Make an OAuth request using flutter

I'm working with bricklink api http://static.bricklink.com/alpha/default/api_wiki.html
I'm unable to implement it in flutter, due to lack of expertise. Here is the request implementation in node.js and I want to replicate this in flutter.
const OAuth = require('oauth');
const fs = require('fs');
const http = require('http');
const host = '127.0.0.1';
const port = '7070';
const server = http.createServer((_req, res) => {
var oauth = new OAuth.OAuth('', '', 'consumer_key', 'consumer_secret', '1.0', null, 'HMAC-SHA1');
oauth.get('https://api.bricklink.com/api/store/v1/categories', 'token_value', 'token_secrete', function(error, data, res) {
if (error) return false;
var json = JSON.parse(data);
saveData(json);
});
function saveData(data) {
const jsonData = JSON.stringify(data);
fs.writeFileSync('inventory.json', jsonData);
res.statusCode = 200 || 201;
// res.setHeader('Content-Type', 'text/plain');
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
res.end('Done');
console.log('Done');
}
});
I want to implement this request in flutter.
Thank You

loging response from server does not work

I am following a tutorial from Coding Garden. There he writes to a database and sends it then back to the client.
When I try to do it, I do not get a respond from the server. I guess there has been a mix up in my code.
When I go to localhost/5000/posts there is no database. Why do I not get an errormessage, or a database?
Best regards
Expected Result:
https://youtu.be/JnEH9tYLxLk?t=3060
client code
const form = document.querySelector('form');
const loadingElement = document.querySelector(".loading");
const API_URL = "http://localhost:5000/posts";
loadingElement.style.display = "none";
form.addEventListener('submit', (event) => {
event.preventDefault();
const formData = new FormData(form);
const name = formData.get('name');
const content = formData.get('content');
const post = {
name,
content
};
form.style.display = "none";
loadingElement.style.display= "";
fetch(API_URL, {
method: "POST",
body: JSON.stringify(post),
headers: {
"content-type": "application/json"
}
}).then(response => response.json())
.then(createdPost => {
console.log(createdPost);
});
});
server code
const express = require("express");
const cors = require('cors');
const monk = require("monk");
const app = express();
const db = monk("localhost/posts");
const posts = db.get("posts");
app.use(cors());
app.use(express.json());
app.get("/", (req, res) => {
res.json({
message: "Post"
});
});
function isValidPost(post){
return post.name && post.name.toString().trim() !== "" &&
post.content && post.content.toString().trim() !=="";
}
app.post("/posts", (req, res) => {
if (isValidPost(req.body)){
const post = {
name: req.body.name.toString(),
content: req.body.content.toString(),
created: new Date()
};
//console.log(post);
posts
.insert(post)
.then(createdPost => {
res.json(createdPost);
});
}else {
res.status(422);
res.json({
message: "Hey, Titel und Inhalt werden benötigt!"
});
}
});
app.listen(5000, () => {
console.log('Listening on http://localhost:5000');
});
You forgot to handle the case when post.insert(...) fails and rejects. In this case no response is sent from your server and the request will hang. Add the following:
posts
.insert(post)
.then(createdPost => {
res.json(createdPost);
})
.catch(err => {
console.log(err);
res.status(500).json({errorMessage: err.message});
});
handle the fetch method with catch. It probably goes to catch.
fetch().then().catch(err => ...)

agent.add not working but console.log working

In below code, "agent.add" is not working but "console.log" is working. I have added promise with resolve and reject, but still its not working. I have tried different ways but multiple response from firestore, not able to send it to user. Able to see logs in firebase but not in dialogflow.
const {Firestore} = require('#google-cloud/firestore');
const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
const {Card, Suggestion} = require('dialogflow-fulfillment');
const admin = require('firebase-admin');
admin.initializeApp();
process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging
statements
const firestore = new Firestore();
const settings = {/* your settings... */
timestampsInSnapshots: true};
firestore.settings(settings);
exports.dialogflowFirebaseFulfillment =
functions.https.onRequest((request, response) => {
const agent = new WebhookClient({ request, response });
console.log('Dialogflow Request headers: ' +
JSON.stringify(request.headers));
console.log('Dialogflow Request body: ' + JSON.stringify(request.body));
const db = admin.firestore();
```
function welcome(agent) {
agent.add(`Welcome to my agent!`); // not working
console.log("Welcome Agent");
const num = agent.parameters.number;
let usersRef = db.collection('add');
let query = usersRef.where('Number', '==', num);
return new Promise((resolve,reject)=>{ // not working
return query.get()
.then(querySnapshot => {
if (querySnapshot.empty) {/*
const timestamp = querySnapshot.get('created_at');
const date = timestamp.toDate();*/
console.log('No matching documents.');
agent.add(`No Matching Documents`);
return;
}
querySnapshot.forEach(doc => {
const line1 = doc.get('Line1');
const line2 = doc.get('Line2');
const explain = doc.get('explanation');
console.log('Line1: ', line1); //this works
console.log('Line2: ', line2); //this works
console.log('explain: ', explain); //this works
agent.add(`your response is ` +doc.get('Line1')); //not working
agent.add(`Final Response - ${line2}`); //not working
agent.add(doc.get('explanation')); //not working
});
resolve('resolved');
})
.catch(err => {
console.log('Error getting documents', err);
reject(err);
});
});
}
Issue is resolved now. Added return statement in the last agent.add and it is working. Thanks.
agent.add(your response is +doc.get('Line1'));
agent.add(Final Response - ${line2});
return agent.add(doc.get('explanation'));