react-native unable to resolve module 'events' - xcode

I have created an empty project with the following command:
react-native init demoProject
after installing
npm install -g react-native-cli
then I have installed mongoDB with the following command:
npm install mongodb --save
In the package.json file I have the following:
"dependencies": {
"events": "^1.1.1",
"mongodb": "^2.2.31",
"react": "16.0.0-alpha.12",
"react-native": "0.47.1"
},
In the index.ios.js file I am trying to import the mongodb as the following:
var MongoClient = require('mongodb').MongoClient;
After building the project in Xcode I have this error:
bundling failed: "Unable to resolve module `events` from `/Users/rzilahi/work/demo01/node_modules/mongodb/lib/apm.js`: Module does not exist in the module map
what am i doing wrong?

Why are you importing MongoClient to index.ios.js ? It shouldn't be imported in the index or any other file of your app. Database queries should be done in a webservice. So in your app, you can use fetch to retrieve data from a webservice and render that with a FlatList or component of choice. You can create a NodeJS project on port 1337 (example port) and run the Node Server. In that Node Project you need to import MongoClient and query the DB for data and use res.send or res.json to send the data back as a response. So if you're able to access your webservice at http://localhost:1337/getdata , you're all set.
You may need to use your actual IP address of the computer in fetch, like:
fetchData(){
fetch('http://192.168.0.4:1337/getdata')
.then((response) => response.json())
.then((responseJson) => {
this.setState({data: responseJson})
})
.catch((error) => {
alert(error);
});
}
And your node server would look something like:
var express = require('express'),
bodyParser = require('body-parser'),
mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/mydb');
var db = mongoose.connection;
mongoose.Promise = global.Promise;
var app = express();
//create the Posts Schema or import it.
app.get("/getdata", function(req, res){
Posts.find({}, function(e,doc){
if(doc==null){
res.send("NO POSTS");
}
else{
res.json(doc);
}
});
});
app.set('port', (process.env.PORT || 1337));
app.listen(app.get('port'), function(){
console.log("Server started on port: " + app.get('port'));
});

Related

What is the easiest way to connect to Memgraph using Node.js?

I want to test the creation of an application that uses Node.js and Memgraph. What is the fastest and easiest way for me to test this type of setup?
The easiest way is to use Express.js. Here are the exact steps:
Create a new directory for your application, /MyApp and position yourself in it.
Create a package.json file using npm init
Install Express.js using npm install express --save and the Bolt driver using npm install neo4j-driver --save in the /MyApp directory. Both packages will be added to the dependencies list.
To make the actual program, create a program.js file with the following code:
const express = require("express");
const app = express();
const port = 3000;
var neo4j = require("neo4j-driver");
app.get("/", async (req, res) => {
const driver = neo4j.driver("bolt://localhost:7687");
const session = driver.session();
try {
const result = await session.writeTransaction((tx) =>
tx.run(
'CREATE (a:Greeting) SET a.message = $message RETURN "Node " + id(a) + ": " + a.message',
{
message: "Hello, World!",
}
)
);
const singleRecord = result.records[0];
const greeting = singleRecord.get(0);
console.log(greeting);
} finally {
await session.close();
}
// on application exit:
await driver.close();
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});
Once you save the file, you can run your program using node program.js.
For additional details check the official Memgraph documentation.

NuxtJS 3 $fetch refuse to connect to local server

I am new to Nuxt3. I tried to connect my Nuxt3 app to my backend site which is built with Laravel. My frontend URL is http://localhost:3000 and my backend is http://localhost:8000. When I connect to http://localhost:8000/api/names using "useFetch" inside a component, it runs fine. But when I do it inside server/api/names.js using $fetch, it shows a 500 (Internal server error).
This runs fine (sample.vue)
const getNames = async () => {
let { data } = await useFetch('http://localhost:8000/api/names')
console.log(data);
}
This does not
(sample.vue)
const getNames = async () => {
let { data } = await useFetch('/api/names')
console.log(data);
}
(/server/api/names.js)
export default defineEventHandler(async (event) => {
const { data } = await $fetch("http://localhost:8000/api/names");
return { data };
});
Here's the code on my Laravel app inside api.php (http://localhost:8000/api/names)
Route::get('/names', function (){
$users_name = User::all()->pluck('name');
return response()->json(['names' => $users_name]);
});
Here's the error that shows when I go to network tab
message: "terminated"
stack: "<pre><span class=\"stack internal\">at Fetch.onAborted (node:internal/deps/undici/undici:11000:53)</span>\n<span class=\"stack\">at Fetch.emit (node:events:513:28)</span>\n<span class=\"stack internal\">at Fetch.terminate (node:internal/deps/undici/undici:10272:14)</span>\n<span class=\"stack internal\">at Object.onError (node:internal/deps/undici/undici:11095:36)</span>\n<span class=\"stack internal\">at Request.onError (node:internal/deps/undici/undici:6477:31)</span>\n<span class=\"stack internal\">at errorRequest (node:internal/deps/undici/undici:8440:17)</span>\n<span class=\"stack internal\">at Socket.onSocketClose (node:internal/deps/undici/undici:7895:9)</span>\n<span class=\"stack\">at Socket.emit (node:events:513:28)</span>\n<span class=\"stack\">at TCP.<anonymous> (node:net:313:12)</span></pre>"
statusCode: 500
statusMessage: ""
url: "/api/names"
I tried to restart both servers hoping that doing this would fix the issue but the problem still persists. Also searched if it has something to do with CORS but it connects when I call the api inside a component.
I had exactly the same problem yesterday and luckily I found a solution without having to downgrade the version of NodeJS because Nuxt3 does not work well under version 16 of Node.
First use Laragon for your Laravel Backend. Laragon automatically creates Hostname for projects ex: laravelbackend.test if the project folder is called "laravelbackend".
Then on the file (/server/api/names.js) replace localhost:8000/api with laravelbackend.test/api
export default defineEventHandler(async (event) => {
const { data } = await $fetch("http://laravelbackend.test/api/names");
return { data };
});

How can I get socket.io to work with deno?

My aim is to get socket.io to work with deno. Deno does have a standard library for web sockets, but that does not have a fail-over.
I think it is possible to use the UNPKG service to use an NPM package in you deno program, but I seem to get the syntax wrong for importing socket.io:
import { serve } from "https://deno.land/std/http/server.ts";
import {Socket} from "https://unpkg.com/browse/socket.io#3.0.1/dist/index.d.ts";
new Worker(new URL("worker.js", import.meta.url).href, { type: "module" });
const server = serve({ port: 3001 });
const app = new Application();
const io = Socket(3001);
// serve index page
if (req.url === "/") {
req.respond({
status: 200,
body: await Deno.open("./public/index.html"),
});
}
io.on("connection", (socket) => {
// either with send()
socket.send("Hello!");
// or with emit() and custom event names
socket.emit("greetings", "Hey!", { "ms": "jane" }, Buffer.from([4, 3, 3, 1]));
// handle the event sent with socket.send()
socket.on("message", (data) => {
console.log(data);
});
// handle the event sent with socket.emit()
socket.on("salutations", (elem1, elem2, elem3) => {
console.log(elem1, elem2, elem3);
});
});
I get the following error:
error: An unsupported media type was attempted to be imported as a module.
Specifier: https://unpkg.com/browse/socket.io#3.0.1/dist/index.d.ts
MediaType: Unknown
It fails because you are importing a .d.ts file, which is a declaration file and essentially you can't run any code from - it's purely to support types.
Instead you should replace index.d.ts with index.js
Try this:
import Socket from 'https://cdn.esm.sh/v9/socket.io#3.0.3/esnext/socket.io.js';
As #Indecisive said, you are importing a .d.ts file.
You can use #Marcos Casagrande: https://stackoverflow.com/a/61821141/6250402 (remember install socket.io module with npm)
Or use https://deno.land/std#0.79.0/ws/mod.ts

How to send the result of graphql query as a file?

I am implementing a graphQL server using Apollo server. I want to send the response of the queries as a text file instead of JSON response. Can anyone help me how to do it in Apollo server.I am using NodeJS for server implementation.
If you would like to use Apollo Server instead of the vanilla graphql library, try adding a plugin into plugins config:
const server = new ApolloServer({
typeDefs,
resolvers,
// You can import plugins or define them in-line, as shown:
plugins: [
{
requestWillStart(reqCtx) {
return {
willSendResponse(ctx) {
ctx.response.http.headers.set('Content-Disposition', 'attachment; filename=result.json');
}
}
}
}
],
})
Reference: https://www.apollographql.com/docs/apollo-server/integrations/plugins/#willsendresponse
For sending File with app Express js :
app.get('/URL', (req, res) => res.download('./yourFile.txt'))
And to write your graphql query result to yourFile.txt
var fs = require("fs");
var data = "your_data_graphql";
fs.writeFile("temp.txt", data, (err) => {
if (err) console.log(err);
console.log("Successfully Written to File.");
});

Unresolved function or method done(), spring with react

Im currently following this https://spring.io/guides/tutorials/react-and-spring-data-rest/ tutorial. But when I write my app.js I get "Unresolved function or method done().
I have tried the other suggestion cleaning cache and add Node.js as global.
What am I missing?
const client = require('./client');
componentDidMount() {
client({method: 'GET', path: '/api/employees'}).done(response => {
this.setState({coaches: response.entity._embedded.employees});
});
}
**Client file **
'use strict';
var rest = require('rest');
var defaultRequest = require('rest/interceptor/defaultRequest');
var mime = require('rest/interceptor/mime');
var uriTemplateInterceptor = require('./api/uriTemplateInterceptor');
var errorCode = require('rest/interceptor/errorCode');
var baseRegistry = require('rest/mime/registry');
var registry = baseRegistry.child();
registry.register('text/uri-list', require('./api/uriListConverter'));
registry.register('application/hal+json', require('rest/mime/type/application/hal'));
module.exports = rest
.wrap(mime, {registry: registry})
.wrap(uriTemplateInterceptor)
.wrap(errorCode)
.wrap(defaultRequest, {headers: {'Accept': 'application/hal+json'}});
The best way is to do this tutorial following the tutor's code. The main trouble is that it is not actual or the author doesn't upgrade it because of his own motives. Anyway, if you look at the package.json you will the version of react in dependecies. So just change the react version
"react": "^15.3.2",
"react-dom": "^15.3.2"
github. Package.json

Resources