I am using apollo-fetch to fetch a graphql data.
I am ending up in a script error and the request does not go through. I an not sure what is going wrong in a fairly simple request like this. Please help.
Here's the error:
Uncaught (in promise) Error: Network request failed to return valid JSON
at throwHttpError (apollo-fetch.js:41)
at apollo-fetch.js:141
at <anonymous>
throwHttpError # apollo-fetch.js:41
(anonymous) # apollo-fetch.js:141
Promise rejected (async)
Here's the code:
const { createApolloFetch } = require('apollo-fetch');
PlayService.prototype.getPlays = function(playID) {
const fetch = createApolloFetch({
uri: 'graphql'
});
const playQuery = `query ($playid: String) {
plays(id: $playid) {
id
items {
nodes {
id
name
}
}
}
}`;
fetch({
query: playQuery,
variables: { playid: playID }
}).then((res) => {
console.log(res.data);
});
};
My best guess is that is that your uri value is incorrect. You should provide a fully qualified uri like this
PlayService.prototype.getPlays = function(playID) {
const fetch = createApolloFetch({
uri: 'http://localhost:3000/graphql'
});
Related
I am trying to create NFT minting project but minting costs 1000000000000000000000. Since it is a big number I want to use bn.js in my project: https://www.npmjs.com/package/bn.js?activeTab=readme
Here how I am doing minting with bn.js
import BN from "bn.js";
const claimNFTs = async () => {
let cost = blockchain.cost;
let gasLimit = CONFIG.GAS_LIMIT;
let totalCostWei = new BN(Number(cost * mintAmount));
let totalGasLimit = String(gasLimit * mintAmount);
setFeedback(`Minting your ${CONFIG.NFT_NAME}...`);
setClaimingNft(true);
blockchain.smartContract.methods
.mint(wallet.account, mintAmount)
.send({
gasLimit: String(totalGasLimit),
to: CONFIG.CONTRACT_ADDRESS,
from: wallet.account,
value: totalCostWei,
})
.once("error", (err) => {
setFeedback("Sorry, something went wrong please try again later.");
setClaimingNft(false);
})
.then((receipt) => {
setFeedback(`WOW, the ${CONFIG.NFT_NAME} is yours!`);
setClaimingNft(false);
});
};
But I am getting an error: bn.js:6 Uncaught (in promise) Error: Assertion failed at assert (bn.js:6:1) at BN._initNumber (bn.js:128:1)
So how can I do minting with big number? Is my approach wrong?
I got this data from backend when try to get a pdf file:
`%PDF-1.7 %���� 5 0 obj <</Filter/FlateDecode/Length 823>>stream x���MS�0���{l���)&���#CCK'!%�ӿߕmb���;�y�Ҿ��K��H�����aN��q��%�Iz&#�i�T
<......>
1950
%EOF\`
How can REACT read and open this as pdf file in a new tab?
NOTE: I'm able to see the PDF file content in postman when call backend endpoint.
I tried this:
Backend controller (Nestjs):
#Get('/getPDF/:uuid')
async getFile(
#Param('uuid') uuid: string,
#Response({ passthrough: true }) res,
): Promise<StreamableFile> {
const resp = await this.service.downloadPDF(uuid);
if (!resp) {
return null;
}
res.header('Content-Type', `application/pdf`);
res.header('Content-Disposition', `attachment; filename="${resp.fileName}`);
return new StreamableFile(resp.buffer); // resp.buffer === Uint8Array
}
Frontend (REACT):
This will call backend api to get pdf file:
getPDF(uuid: string): Promise<AxiosResponse<Blob>> {
return this.httpClient.get(`${this.apiUrlPath}/getPDF/${uuid}`, {
responseType: 'blob',
});
}
This was supposed to render the pdf file
const response = await api.getPDF(uuid);
window.open(URL.createObjectURL(response.data));
I got this error:
TypeError: Failed to execute 'createObjectURL' on 'URL': Overload resolution failed.
UPDATED
Change AxiosResponse type from Blob to ArrayBuffer and create a new Blob from that buffer, solves the issue
This works:
getPDF(uuid: string): Promise<AxiosResponse<ArrayBuffer>> {
return this.httpClient.get(`${this.apiUrlPath}/getPDF/${uuid}`, {
responseType: 'arraybuffer',
});
}
const response = await api.getPDF(uuid);
const blob = new Blob([response.data], { type: "application/pdf" });
window.open(URL.createObjectURL(blob));
Thanks amir sarfar
Try passing a blob to createObjectURL:
const response = await api.getPDF(uuid);
const blob = new Blob([response.data], { type: "application/pdf" });
window.open(URL.createObjectURL(blob));
Im making a Discord Bot Dashboard and implementing Discord OAuth2. I'm following the guide here: https://discordjs.guide/oauth2/#a-quick-example and the code is essentially the same.
async getJSONResponse(body) {
let fullBody = '';
for await(const data of body) {
fullBody += data.toString();
}
return JSON.parse(fullBody)
}
async getAccessToken(code) {
if (code) {
try {
let body = new URLSearchParams();
body.append('client_id', environment.discord.clientId)
body.append('client_secret', environment.discord.clientSecret)
body.append('code', code)
body.append('grant_type', 'authorization_code')
body.append('redirect_uri', environment.discord.redirect)
body.append('scope', 'identify')
let options = {
headers: new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
};
const tokenResponseData = await this.http.post('https://discord.com/api/oauth2/token', body.toString(), options)
const oauthData = await this.getJSONResponse(tokenResponseData.body)
console.log(oauthData)
} catch(err) {
console.error('an error')
console.error(err)
}
}
}
However, I get this error: Property 'body' does not exist on type 'Observable<Object>'.
As you can see, the guide above clearly shows that body does in fact exist on the object.
I'm out of ideas, any help is appreciated.
Thanks
May I know what is the problem with my code for the backend. I try to create a place and update it in the user database. The problem is If I only have 1 user. The database can create and update the data but if I have more than 2 then, the data cannot be updated or created. Here is my code. I have been working on this part for so long, that I cannot find the solution.
const createFile = async (req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return next(
new HttpError('Invalid inputs passed, please check your data.', 422)
);
}
const { userId, Dataset } = req.body;
const createdFile = new File({
userId,
Dataset,
});
let user;
try {
user = await User.findById(userId);
} catch (err) {
const error = new HttpError(
'Creating place failed, please try again 1',
500
);
return next(error);
}
if (!user) {
const error = new HttpError('Could not find user for provided id', 404);
return next(error);
}
try {
const sess = await mongoose.startSession();
sess.startTransaction();
await createdFile.save({ session: sess });
user.Dataset.push(createdFile);
await user.save({ session: sess });
await sess.commitTransaction();
} catch (err) {
const error = new HttpError(
'Creating place failed, please try again.2',
500
);
return next(error);
}
res.status(201).json({ files: createdFile });
};
The error message that I got
Error: User validation failed: _id: Error, expected `_id` to be unique. Value: `62c661c629d1cb99768efd05`
at ValidationError.inspect (C:\Users\acit\Desktop\FYP Code\FYP Code\backend2\node_modules\mongoose\lib\error\validation.js:48:26)
at internal/per_context/primordials.js:23:32
at formatValue (internal/util/inspect.js:783:19)
at inspect (internal/util/inspect.js:337:10)
at formatWithOptionsInternal (internal/util/inspect.js:2016:40)
at formatWithOptions (internal/util/inspect.js:1898:10)
at console.value (internal/console/constructor.js:323:14)
at console.log (internal/console/constructor.js:358:61)
at createFile (C:\Users\acit\Desktop\FYP Code\FYP Code\backend2\controllers\files-controller.js:102:13)
at processTicksAndRejections (internal/process/task_queues.js:93:5) {
errors: {
_id: ValidatorError: Error, expected `_id` to be unique. Value: `62c661c629d1cb99768efd05`
at validate (C:\Users\acit\Desktop\FYP Code\FYP Code\backend2\node_modules\mongoose\lib\schematype.js:1321:13)
at C:\Users\acit\Desktop\FYP Code\FYP Code\backend2\node_modules\mongoose\lib\schematype.js:1297:24
at processTicksAndRejections (internal/process/task_queues.js:93:5) {
properties: [Object],
kind: 'unique',
path: '_id',
value: new ObjectId("62c661c629d1cb99768efd05"),
reason: undefined,
[Symbol(mongoose:validatorError)]: true
}
},
_message: 'User validation failed'
}
It already settle, I reroll the mongoose-unique-validator to 2.0.3 version
I use this command
npm install mongoose-unique-validator#2.0.3 --legacy-peer-deps
hope that someone with same issues as mine find my post and can help them to solve the same issues
I'm getting a value as params when I make an axios GET request and I want to use that value to make a sql query. This is the code:
#app.route('/get-hcp-data', methods=['GET', 'POST'])
def get_hcp_data():
value = request.args.get('nameValue')
engine = connect_pg()
sql = "select * from dim_hcp_details where hcp_name like " + value + "%"
hcp_details = pd.read_sql_query(sql,engine)
hcp_dict = hcp_details.to_dict()
print(hcp_dict)
return jsonify(hcp_dict)
When I press the button 'a', I'm getting this error in the terminal of Flask: [SQL: select * from dim_hcp_details where hcp_name like a%]
(Background on this error at: http://sqlalche.me/e/13/f405)
Just for reference here is the axios get request that I'm executing in the front end using ReactJS.
fetchingDataOnChange = () => {
let nameValue = this.state.searchName;
console.log('Name inside fetchingdata: ', nameValue);
axios.get('/get-hcp-data?', {
params: {
nameValue: nameValue,
}
})
.then((response) => {
console.log(response);
}, (error) => {
console.log(error);
});
}
I came up with a solution like this. First, I sent a post request instead of a get request using Axios inside my React Component like this:
fetchingDataOnChange = () => {
let nameValue = this.state.searchName;
var myParams = {
nameValue: nameValue
}
axios.post('/get-hcp-data', myParams)
.then((res) => {
const hcps = res.data;
this.setState({ hcps: hcps, hcpName:
Object.values(hcps.hcp_details_concat) })
Object.values(this.state.hcps.hcp_details_concat));
console.log(res);
}, (error) => {
console.log(error);
});
}
I then wrote my Flask code in this manner to get the data from axios. Used request.get_json to get every keystroke and executed a SQL query based on that.
#app.route('/get-hcp-data', methods=['GET', 'POST'])
def get_hcp_data():
value = request.get_json()
newValue = value['nameValue']
engine = connect_pg()
sql = "select * from dim_hcp_details where lower(hcp_name) like
lower('"+newValue+"%') limit 50"
hcp_details = pd.read_sql_query(sql,engine)
hcp_details['hcp_details_concat'] = "[" + hcp_details['hcp_id'] + "]" +
hcp_details['hcp_name']
hcp_dict = hcp_details.to_dict()
return jsonify(hcp_dict)