Hi guys i am new in nodejs when i am trying to run my node js file then Am getting an error like coneection closed due to error Error: Unsupported protocol "undefined" don't know where i am wrong please fix my error
https://ibb.co/31J6xWS
index.js
const http = require("http");
const fs = require("fs");
var requests = require("requests");
const homeFile = fs.readFile("home.html", "utf-8",(err)=>{
console.log("Sucessfully");
});
const server = http.createServer((req, res) => {
if (req.url == "/") {
requests(
"{API}",
)
.on("data", (chunk) =>{
console.log(chunk);
})
.on("end", (err) => {
if (err)
return console.log("coneection closed due to error",err);
console.log("end");
});
}
})
server.listen(8000,"127.0.0.1")
You have made a mistake in your pasting API key. Check your API key it will not be like URL.
http:// is missing at the beginning.
Add http:// in the start of your API key.
Are u trying to use a template literal on line 13... the "{API}" section. If so it should ${API} with backticks. And you need to import it from the file you have it in. Beginner to Node.js as well, and I have used something similar to this. Hope it helps. Have u seen https://www.npmjs.com/package/request? Might help you.
a better and easier way to build a server is by using Express.js library you can download it with the following command:
npm i express
more information: https://www.npmjs.com/package/express
after that you can build a server very easily with the following code :
// npm install express
const express = require('express');
const app = express();
app.get('/', (req, res)=> {
res.send('Hello World');
})
app.listen(3000,()=>{
console.log("starting...");
});
the following code is create a server listening on localhost port 3000 and print a message hello world
I was also facing the same problem. Here is the solution. Replace {API} with your API key.
requests("replace this with your API url and API key")
Related
I keep gettings the Error Unexpected token '?' when using NodeJS and Firebase Functions. I don't have any '?' token in my code, so think it's in the node_modules. I pasted my code below.
const functions = require("firebase-functions");
const express = require('express');
const fs = require('fs');
const app = express();
// 99 Names of Allah
app.get('/99Names', (req, res) => {
res.send(JSON.parse(fs.readFileSync('99namesofallah.json')));
});
// Duas
app.get('/duas', (req, res) => {
res.send(JSON.parse(fs.readFileSync('dua/duas.json')));
});
app.get('/duas/:edition', (req, res) => {
const edition = req.params.edition;
res.send(JSON.parse(fs.readFileSync(`dua/${edition}.json`)));
});
app.listen(3000, () => {
console.log('API listening on port 3000');
});
exports.app = functions.https.onRequest(app)
I tried paring my code and checking the packages, but was unable to find a '?' token.
For anyone else experiencing this problem. It seems Firebase Functions and NodeJS put together do not like optionals. I had to edit a few files and simply changed the optional to a null/undefined check.
The following are the files where I found the error coming from:
firebase-app.js
firebase-namespace.js
So I have a node js code that updates and modifies a file content but I would like the data being inserted to come from a JavaScript code. How do I connect the two? Basically how do I have a function in node js that can be called from JavaScript?
Considering there's not much information to go off in the question, I am going to make a the assumption that you're trying to pass information from JS in a web browser to a node application.
The easiest and best documented way to do this would be to set up a simple web server using a package like expressJS and send data as a POST request using the fetch command in the browser.
Install express on the node application using the getting started guide
Write a http path where you can process the data
Start the node app
Make a call to the path we just created
Example backend code:
const express = require('express')
var bodyParser = require('body-parser')
const app = express()
const port = 3000
app.use(bodyParser);
app.post('/mypath', (req, res) => {
const myInputData = req.body.data;
//Do whatever you want with the data
})
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
Example front-end code:
var data = new FormData();
data.append('data', YOUR_DATA_VAR_HERE)
var options = {
method: 'POST',
body: data
}
fetch('http://localhost:3000/mypath',options)
.then(function(response){ console.log("Data was sent successfully") })
.catch(function(error) { console.log("There was an error sending data") })
I am trying to pipe an image response from an internal API, using NodeJS Express to an external endpoint. I.e. proxying an image.
This is what I have tried, but I keep getting an empty box instead of the image:
app.get('/image', (req, res) => {
res.setHeader('Content-Type', 'image/png');
request.get(`http://localhost:8080/image`).pipe(res);
// Also tried reading from a file and not the endpoint
//to make sure it's not a problem with "request" library with same results
//fs.createReadStream('./image.png').pipe(res);
});
Using browser dev tools I can also see that the size of the empty image I get on the external endpoint is bigger then that of the working image got from the internal endpoint.
Accessing the endpoint from "Postman" seems to give the image without problems, but accessing from Firefox says that the image has errors.
So it seems to be some kind of an encoding issue which I can't seem to figure out how to fix. Please help.
Can't reproduce your issue. The below example works fine. Testing environment:
Microsoft Edge 86.0.622.38
E.g.
server-internal.ts:
import express from 'express';
import fs from 'fs';
import path from 'path';
const app = express();
const port = 8080;
app.get('/image', (req, res) => {
console.log('internal server /image');
res.setHeader('Content-Type', 'image/png');
fs.createReadStream(path.resolve(__dirname, './image.png')).pipe(res);
});
app.listen(port, () => console.log('HTTP server is listening on port:', port));
server-external.ts:
import express from 'express';
import request from 'request';
const app = express();
const port = 3000;
app.get('/image', (req, res) => {
console.log('external server /image');
res.setHeader('Content-Type', 'image/png');
request.get(`http://localhost:8080/image`).pipe(res);
});
app.listen(port, () => console.log('HTTP server is listening on port:', port));
Access http://localhost:3000/image, got the image correctly.
The logs of the internal server:
HTTP server is listening on port: 8080
internal server /image
The logs of the external server:
HTTP server is listening on port: 3000
external server /image
source code: https://github.com/mrdulin/expressjs-research/tree/master/src/stackoverflow/64302729
Thank you slideshowp2 for taking your time and pointing out that, my provided code should indeed work.
It would have been impossible to figure out the issue with the info that I gave.
I was using "livereload" middleware in my project.
This middleware intersects all the responses coming from my server and tries to inject the liverelad script into them.
By default it is configured to ignore responses for endpoints ending with ".png" and other image and binary formats.
Adding ".png" to the endpoint path, solved the issue.
app.get('/image.png', (req, res) => {
request.get(`http://localhost:8080/image`).pipe(res);
});
Im a beginner with node.js so bear with me please :D
Simple task: I use express and I want to send an array, lets say ["item1", "item2"] from a node server to a client that calls the server with a get method. When I tried this, I stumbled upon the CORS error.
I also thought about doing a this through a post:
-client:
$(document).ready(function () {
$(".testButton").click(function (e) {
e.preventDefault();
$.ajax({
url: "http://localhost:3000/test_post",
type: "post",
data: "sent",
success: function () {}
});
});
-server:
app.post('/Quiz_post', function (req, res) {
res.send(["item1", "item2"]);
});
But this also doesnt work. Now I am trying to use cross-fetch client side. Could you please guide me a bit? Thanks!
Add this code in ur app.js to enable CORS.
npm i cors in the project 1st
var cors = require('cors');
var app= express(); //After this line of code add the code below
app.use(cors());
I am trying to capture current GET URL and query params in node.js code. I jut realized windows.loication does not work in node.js as it is for client-based execution only. I have tried multiple things but am not able to capture the GET request. Here is what all I have tried.
var url = require('url');
var url_parts = url.parse(request.url, true);
var query = url_parts.query;
var request = require('request');
var query = url.parse(request.url,true).query;
getFormattedUrl(req);
function getFormattedUrl(req) {
console.log("req.url: " + req.url);
return url.format({
protocol: req.protocol,
host: req.get('host')
});
}
All of these fail for me, giving the errors like :
2016-12-17T03:32:36.164600+00:00 app[web.1]: ReferenceError: request is not defined
2016-12-17T03:43:46.569603+00:00 app[web.1]: ReferenceError: request is not defined
2016-12-17T03:45:14.509168+00:00 app[web.1]: TypeError: Parameter 'url' must be a string, not undefined
Can someone pls suggest how to cpature the GET params in node.js.
If you are using express 4.x then you want req.query
If you are trying to capture the request that is being made from a NODE JS server to another http/https endpoint for debugging or viewing purposes, this might help
var options2 = {
url: "https://www.google.com",
port: '443',
method: 'GET'
}
request(options2, function(error, response){
console.log(options2);
});
where options2 is the defined URL the node js server is trying to reach
When you console log options2 (a variable name i've used, you can call it anything), it will give you all the information about the HTTPS/HTTP call the server is making.
Sample Express JS 4 Code
var express = require('express')
var app = express()
app.get('/', function (req, res) {
res.send('Someting')
console.log(req.query);
})
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
})
This will launch a localhost server on port 3000
If you do localhost:3000?q=test you will see
{q: test}
in the console/log.
To fix the problem above, just install request module from the command line first, before using it:
npm install request
Interesting things is that to achieve what you need, you do not need to use request module at all. Just use url module as you did above, pass request object (not a module, but actual calling request), and format it using url.format
const url = require('url')
function getFormattedUrl(req) { return url.format(req.url) }