I try to make queries using the cloud code feature of our Parse server. Unfortunately we could not retrieve any data from the database. Our code looks as follows:
main.js:
Parse.Cloud.define('test', function(request, response) {
var user = request.user;
var token = user.getSessionToken();
var query = new Parse.Query('Carpark');
query.first({ sessionToken: token }) // pass the session token to find()
.then(function(messages) {
response.success(messages);
}, function(error) {
response.error(error);
});
});
index.js:
var express = require('express');
var ParseServer = require('parse-server').ParseServer;
var path = require('path');
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
var api = new ParseServer({
databaseURI: 'mongodb://parse-server:[...]#localhost:27017/[...]',
cloud: __dirname + '/cloud/main.js',
appId: '[...]',
masterKey: '[...], //Add your master key here. Keep it secret!
serverURL: 'https://backend.[...]/parse', // Don't forget to change to https if needed
publicServerURL: 'https://backend.[...]/parse', // Don't forget to change to https if needed
liveQuery: {
classNames: ["Posts", "Comments"] // List of classes to support for query subscriptions
}
});
// Client-keys like the javascript key or the .NET key are not necessary with parse-server
// If you wish you require them, you can set them as options in the initialization above:
// javascriptKey, restAPIKey, dotNetKey, clientKey
var app = express();
//var basicAuth = require('basic-auth-connect');
//app.use(basicAuth('triveme', 'triveme'));
app.use('/', express.static(path.join(__dirname, '/public')));
app.use('/parse', api);
app.get('/test', function(req, res) {
res.sendFile(path.join(__dirname, '/public/test.html'));
});
var port = 61004;
var httpServer = require('http').createServer(app);
httpServer.listen(port, function() {
console.log('parse-server-example running on port ' + port + '.');
});
// This will enable the Live Query real-time server
ParseServer.createLiveQueryServer(httpServer);
Example request from iOS-App:
PFCloud.callFunction(inBackground: "test", withParameters: nil) {
(response, error) -> Void in
if let response = response {
let result = response
print("Cloud data:", result )
}
if error != nil {
print(error ?? "default cloud function error")
}
}
I don't get any feedback from server (no response and no error). What is a possible problem of my issue?
Log request with verbose = 1:
REQUEST for [POST] /parse/functions/test: {} method=POST, url=/parse/functions/test, host=localhost:61004, accept=*/*, x-parse-session-token=[...], x-parse-application-id=[...].platform.dev2, x-parse-installation-id=[...], x-parse-os-version=10.2 (16D32), accept-language=en-us, accept-encoding=gzip, deflate, x-parse-client-version=i1.14.2, user-agent=trive.park/8 CFNetwork/808.2.16 Darwin/16.4.0, x-parse-app-build-version=8, x-parse-app-display-version=1.0, x-forwarded-for=[...], x-forwarded-host=backend.[...], x-forwarded-server=backend.[...], connection=Keep-Alive, content-length=0,
Log Response:
4|trive-pa | error: Failed running cloud function test for user nZ76ZimELw with:
4|trive-pa | Input: {}
4|trive-pa | Error: {"code":141,"message":{"code":100,"message":"XMLHttpRequest failed: \"Unable to connect to the Parse API\""}} functionName=test, code=141, code=100, message=XMLHttpRequest failed: "Unable to connect to the Parse API", user=nZ76ZimELw
4|trive-pa | error: Error generating response. ParseError {
4|trive-pa | code: 141,
4|trive-pa | message:
4|trive-pa | ParseError {
4|trive-pa | code: 100,
4|trive-pa | message: 'XMLHttpRequest failed: "Unable to connect to the Parse API"' } } code=141, code=100, message=XMLHttpRequest failed: "Unable to connect to the Parse API"
4|trive-pa | [object Object]
parse-server version: 2.2.23
self hosted on Apache Server
MongoDB
Related
i was trying to create wss server in using nestjs,but when i finished all configuration in a new nestjs project and tried to connect to the server via 'wss://localhost:port', i got the error below:
WebSocket connection to 'wss://localhost:10033/' failed:
enter image description here
and the main.ts is like this:
async function bootstrap() {
const {key, cert} = await readKeyAndCert()
const app = await NestFactory.create(AppModule, {
httpsOptions: {
requestCert: false,
rejectUnauthorized: false,
key,cert
}
});
app.enableCors()
app.useWebSocketAdapter(new WsAdapter(app))
app.useGlobalFilters(
new HttpExceptionFilter()
)
await app.listen(HTTP_PORT);
}
what can i do to fix the wss:// connection?
I have implemented cloudflare on a live website, the website has a socket server that's setup with socket.io and express, everything were working fine before implementing cloudflare
Currently I'm using port: 2053 which i've allowed access to through Laravel forge
socket.js
var app = require('express')();
const fs = require('fs');
var server = require('https').createServer({
key: fs.readFileSync('/etc/nginx/ssl/mywebsite.com/1234/server.key'),
cert: fs.readFileSync('/etc/nginx/ssl/mywebsite.com/1234/server.crt'),
}, app);
var io = require('socket.io')(server, {
cors: {
origin: function(origin, fn) {
if (origin === "http://mywebsite.test" || origin === "https://mywebsite.com") {
return fn(null, origin);
}
return fn('Error Invalid domain');
},
methods: ['GET', 'POST'],
'reconnect': true
},
});
var Redis = require('ioredis');
var redis = new Redis();
redis.subscribe('asset-channel', () => {
console.log('asset-channel: started');
});
redis.on('message', function(channel, message) {
var message = JSON.parse(message);
io.to(message.data.id).emit(channel + ':' +message.event + ':'+ message.data.id, message.data);
});
io.on("connection", (socket) => {
socket.on("join:", (data) => {
socket.join(data.id);
});
socket.on("leave:", (data) => {
socket.leave(data.id);
});
});
server.listen(2053, () => {
console.log('Server is running!');
});
app.js
if (! window.hasOwnProperty('io')) {
// if (
// window.origin === "http://mywebsite.test" ||
// window.origin === "https://mywebsite.com" ||
// window.origin == "https://mywebsite.test"
// ) {
window.io = io.connect(`${window.origin}:2053`);
window.io.on('connection');
// }
}
As mentioned before everything were working fine before implementing cloudflare and i have tried to read some different documentation like:
https://developers.cloudflare.com/cloudflare-one/policies/zero-trust/cors
https://socket.io/docs/v4/handling-cors/
I found many different problems similar online, and tried several solutions but nothing seem to make the socket connection work
Tried to allow all cors like so:
var io = require('socket.io')(server, {
cors: {
origin: "*",
methods: ['GET', 'POST'],
'reconnect': true
},
});
Didn't work either, tried configure some stuff in nginx which didn't work either
Error
Access to XMLHttpRequest at 'https://mywebsite.com:2053/socket.io/?EIO=4&transport=polling&t=NurmHmi' from origin 'https://mywebsite.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I think i might have to configure something in the cloudflare dashboard, i just dont know what and my googling skills could not take me to the finish line this time around.
Im not too experienced with sockets so it would be awesome if there are some skilled socket expert who have had this issue before who can guide me in the correct direction? :)
I made it run by adding this to the app.js:
window.io = io.connect(`${window.origin}:2053`, { transports: ["websocket"] });
Apparently it will try to use polling instead of websocket.
I have a flutter web app that I am running on localhost to debug, my web app posts data to my Firebase Cloud functions API which then sends data to Google Bigquery to create a table, although I have installed CORS already I keep getting this error in my browser below
Access to XMLHttpRequest at 'https://us-central1-denance-cbf3f.cloudfunctions.net/api/create_table' from origin 'http://localhost:55073' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
us-central1-denance-cbf3f.cloudfunctions.net/api/create_table:1 Failed to load resource: net::ERR_FAILED
errors.dart:202 Uncaught (in promise) Error: XMLHttpRequest error.
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/patch/core_patch.dart 897:28 get current
packages/http/src/browser_client.dart 71:22 <fn>
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/zone.dart 1687:54 runUnary
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 155:18 handleValue
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 707:44 handleValueCallback
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 736:13 _propagateToListeners
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 533:7 [_complete]
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/stream_pipe.dart 61:11 _cancelAndValue
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/stream.dart 1219:7 <fn>
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/operations.dart 324:14 _checkAndCall
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/operations.dart 329:39 dcall
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/html/dart2js/html_dart2js.dart 37324:58 <fn>
at Object.createErrorWithStack (:55073/dart_sdk.js:5070)
at Object._rethrow (:55073/dart_sdk.js:37715)
at async._AsyncCallbackEntry.new.callback (:55073/dart_sdk.js:37711)
at Object._microtaskLoop (:55073/dart_sdk.js:37568)
at _startMicrotaskLoop (:55073/dart_sdk.js:37574)
at :55073/dart_sdk.js:33324
this is my code below
const functions = require("firebase-functions");
const express = require('express');
var cors = require('cors');
const { BigQuery } = require('#google-cloud/bigquery');
const bigquery = new BigQuery();
var app = express();
app.use(cors);
app.use(express.json());
exports.api = functions.https.onRequest(app);
app.post('/create_table', cors(dynamicCorsOptions), function (req, res,) {
'use strict';
async function createTable() {
let schema = [];
async function groupUp() {
for (let key in req.body) {
schema.push({ name: req.body[key]['name'], type: req.body[key]['type'] });
}
}
await groupUp();
await doingIt();
async function doingIt() {
var datasetId = 'denanse'; // Existing dataset
var tableId = 'hrhrhhh'; // Table to be created
const options = {
schema: schema,
location: 'US',
};
const [table] = await bigquery
.dataset(datasetId)
.createTable(tableId, options);
console.log(`Table ${table.id} created.`);
res.send(`Table ${table.id} created.`);
}
}
createTable();
});
how can I resolve this?
Currently your usage of the cors package is bugged in two ways. You only need to implement either of the below fixes.
Enable CORS on all routes
Because you've imported and used the cors package like so:
var cors = require('cors');
// ...
app.use(cors);
You've attached the cors constructor to the Express application rather than an instance of the cors middleware (You are calling cors(options) with cors(request)). The options object and its properties are covered in the documentation.
In its most basic form, you can use no configuration to allow CORS on all requests:
app.use(cors())
However, this is effectively the same as just manually setting the CORS headers yourself to * along with some other headers.
This is unsecure and goes against the point of CORS. You should instead configure it so that you only accept a handful of origins related to your project.
/** The current project's ID */
export const PROJECT_ID = JSON.parse(process.env.FIREBASE_CONFIG).projectId;
/** Array of permitted origins for CORS */
export const CORS_ALLOWED_ORIGINS = [
"https://my.custom.domain", // 0+ custom domains related to your project
`https://${PROJECT_ID}.firebaseapp.com`, // legacy Firebase Hosting domain
`https://${PROJECT_ID}.web.app`, // modern Firebase Hosting domain
...(process.env.NODE_ENV === "production"
? []
: ["localhost", "undefined"] // permit CORS on localhost, only while emulated
),
];
app.use(cors({ origin: CORS_ALLOWED_ORIGINS }))
Enable CORS only on /create_table
Similar to above, you've attached the cors() middleware to the /create_table route using:
app.post('/create_table', cors(dynamicCorsOptions), function (req, res) { /* ... */ });
Here, dynamicCorsOptions is undefined (at least in the code you've shared) which will use the CORS middleware on requests to POST /create_table. However, you need to handle OPTIONS /create_table too.
// handle preflight requests
app.options('/create_table', cors(dynamicCorsOptions));
// handle actual requests
app.post('/create_table', cors(dynamicCorsOptions), function (req, res) { /* ... */ });
You can even use cors({ origin: CORS_ALLOWED_ORIGINS }) from the above section for this.
Other points
The Functions Framework (that runs your function), as documented here, parses the body of the request for you if it is set with the appropriate headers. This means you don't need app.use(express.json()).
Your code calls createTable() but doesn't handle if it fails which will throw an unhandled Promise exception and terminate your function. You can either handle this case using catch() or the try/catch block in the next snippet:
createTable()
.catch((err) => {
console.error("Failed to create table: " + err.code || err.message, err);
res.status(500)
.send("Failed to create table with unknown error");
});
Currently the execution of your /create_table handler jumps around quite a bit, I propose rearranging it for readability:
app.post('/create_table', cors(dynamicCorsOptions), function (req, res) {
'use strict';
// this could be moved outside of the handler
async function groupUp(requestBody) {
const groups = [];
for (let key in requestBody) {
const { name, type } = requestBody[key];
groups.push({ name, type });
}
return groups;
}
// this could be moved outside of the handler
async function createTableInDataset(datasetId, schema) {
const tableId = /* generate table ID */;
const [table] = await bigquery
.dataset(datasetId)
.createTable(tableId, {
schema,
location: 'US',
});
return table.id;
}
async function createTable() {
try {
const schema = await groupUp(req.body);
const createdTableId = createTableInDataset('denanse', schema);
console.log(`Table ${createdTableId} created.`);
res.status(201)
.send(`Table ${createdTableId} created.`);
} catch (err) {
console.error("Failed to create table: " + err.code || err.message, err);
res.status(500)
.send("Failed to create table with unknown error");
}
}
createTable();
});
I followed the instructions for connecting cassandraDB and expressJs (V4.16.1) here -> https://expressjs.com/en/guide/database-integration.html#cassandra
but I am having this error in the browser:
msg
name "ArgumentError"
info "Represents an error that is raised when one of the arguments provided to a method is not valid."
message "'localDataCenter' is not defined in Client options and also was not specified in constructor. At least one is required. Available DCs are: [datacenter1]"
code index.js
var express = require('express');
var router = express.Router();
var cassandra = require('cassandra-driver');
var client = new cassandra.Client({ contactPoints:['localhost'] });
client.connect(function(err, result){
console.log('cassandra connection done');
});
var getAlllogs = 'SELECT * FROM logs.ourlogs';
/* GET home page. */
router.get('/', function(req, res, next) {
//res.render('index', { title: 'Express' });
client.execute(getAlllogs,[], function(err, result){
if(err){
res.status(404).send({msg:err});
} else{
res.render('index', {
ourlogs: result.rows[0]
})
}
});
});
module.exports = router;
code index.jade
extends layout
block content
h1 all logs
ul
each ourlog, i in ourlogs
li #{ourlog.curTime}
cassandra info
Connected to Test Cluster at 127.0.0.1:9042.
[cqlsh 5.0.1 | Cassandra 3.11.6 | CQL spec 3.4.4 | Native protocol v4]
Use HELP for help.
cqlsh>
what did I miss?
This is the answer :
var client = new cassandra.Client({ contactPoints: ['127.0.0.1'], localDataCenter: 'datacenter1', keyspace: 'yourkeyspacename' });
ExpressJS team should edit it on their website
I'm setting up a server for a project that I've been trying to develop on my own, and using SQLite and Node.js as the database type and server platform, respectively. I'm relatively new to backend development, and I am trying to set up a POST request from the frontend of the webpage to the backend so whatever the user submits will store in "comments.db", a file in the server which will store all the username and data (specifically the user ID and data).
In the past, I've tried renaming the database differently, and moving the database into several different subfiles, but I always yield the same error on submission.
The following is my code for my node.js file:
var os = require( 'os' );
const interfaces = os.networkInterfaces();
const addresses = [];
var getMacAddress;
var request = require('request');
var express = require('express');
var sqlite3 = require('sqlite3');
var bodyParser = require('body-parser');
var ip = require("ip");
var address = ip.address();
var db = new sqlite3.Database('comments.db');
var app = express();
app.use(express.static(__dirname));
app.use(bodyParser.urlencoded({extended: false}));
app.get('/comments', function(request, response){
// response.send('Hello Worlds');
response.send("Hello my name is aestheticnoodle and you have reached a wrong");
});
app.get('/comments', function(request, response){
console.log('GET request received at /alpha');
db.all('SELECT * FROM comments', function(err, rows){
if(err){
console.log("Error");
} else {
response.send(rows);
//pass rows back to the client
}
});
});
//runs once a user submits a comment
app.post('/comments', function(request, response){
db.run('INSERT INTO comments VALUES (?, ?)', ["aestheticnoodle" ,request.body.action], function(err, rows){
if(err){
console.log(request.body.action);
console.log("INSERT INTO " + err);
} else {
response.status(200).redirect('chat.html');
}
});
});
app.listen(3000, function(){
console.log("Server is running on port 3000");
});
var admin = require("firebase-admin");
var firebaseConfig = {
apiKey: "baseapp",
authDomain: "fire",
databaseURL: "inthe,
projectId: "data",
storageBucket: "",
messagingSenderId: "private",
appId: "some2"
};
admin.initializeApp(firebaseConfig);
var headers = {
'App-Id': 'someappid',
'App-Key': 'someappkey',
'Content-Type': 'application/json'
};
var dataString = '{"text": "test run.."}';
var options = {
url: 'https://somesite.com/v2/parse',
method: 'POST',
headers: headers,
body: dataString
};
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
}
request(options, callback);
and the error is as follows:
C:\Users\achu1\Music\projectsummer2019\cybeRx>node nodeRequest.js
Server is running on port 3000
undefined
INSERT INTO Error: SQLITE_ERROR: no such table: comments
here is the javascript snippet where I try to insert html in the interface of a chat bot:
var string = "What seems to be the problem you have been experiencing? Use one of the keywords, per SymptomList the complete list of symptoms."
document.getElementById("chat").innerHTML += '<form action = "/comments" method = "POST">'+ "<div id = \"botLog\" class = \"chatting\">" + string + '<textarea rows = "15" name = "comment"> Write stuff here' + '</textarea>'+ '<br><br><input type = "submit" value = "SUBMIT"/></form>' + "</div><br>";
as you can see, I attempted to connect my database and my html file running in the localhost by making a POST method form into my comment.db file, which is actually in my directory.
https://imgur.com/a/pdGAVhm
why does the node say that there is no such database to execute the POST command, and how do I resolve this problem so my textbox data saves to the database?