I'm using an AngularJs, node & socket.io to write an app where I want to have some shared data in my different clients. I'm looking at this example: https://github.com/mhevery/angular-node-socketio
I get everything up and running and it works fine if I go to the location of my index.html in my file system (c:/user/angularnodesocket/index.html), but when I go to localhost:8888 the site still shows but the angular stuff is not interpretated.
I get this error on localhost
Resource interpreted as Script but transferred with MIME type text/html: "http://localhost:8888/bower_components/angular/angular.js". localhost/:4
Uncaught SyntaxError: Unexpected token < :8888/bower_components/angular/angular.js:1
Can anyone help me with what's going on here?
//G
In that example you are using the following code
http.createServer(function (request, response) {
fs.readFile(__dirname+'/public/index.html', function (err, data) {
if (err) throw err;
response.setHeader("Content-Type", "text/html");
response.end(data);
});
}).listen(8888);
returns index.html whatever the request is. Your browser requests angular.js file, but index html is returned instead which causes the error messages you see.
You have to modify server.js code to support static files.
Related
I'm using express and trying to download a file, then load the page. I understood that the problem is stopping res.download with res.render but I can' t figure out how to resolve this. I also tried to put res.render() inside the callback function of res.download(), the only thing that happen is that res.render stopped working but the file would download.
app.get("/", function(req, res) {
res.download(
"./public/sample-zip/Lost Sky - Dreams.zip",
"Lost Sky - Dreams.zip",
err => {
if (err) console.log("Errore nel dw: " + err);
}
);
res.render("index");
});
You can't end the same request in multiple ways - download behind the scenes will call sendFile which sends a file to the client and ends the request, similarly render will send page content and also end the request.
The correct approach here is to allow the file to be downloaded to the client and then have the client redirect the page on the back of a successful download.
I am executing following simple node js code
var http = require('http');
http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type':'text/plain'});
res.end('Hello Node JS');
console.log('printing the message');
}).listen(8080);
After executing the command node sample.js and
hitting the url on browser http://localhost:8080/
I am getting the console log statement twice on the command prompt as printing the message
Any Suggestions
EDIT:
Interestingly After checking on other browsers i.e. Firefox, IE no favicon.ico request is made on network tab and console message is printed only once.
As I understood, using express module is better option to handle requests in a typical web application
check the Network area of your browser's developer console to find out what requests are being made. I imagine you will see two:
GET /
GET /favicon.ico
your HTTP server is coded to respond to all requests by printing to console; so if you see two requests, you get two console messages.
i'm developing an application with nodejs. I have to read a local file on server, i'm using this function:
fs.readFile(path, "utf8", function (err,data) {}
how i can serve the 'data' to client? is good to open it in a new tab or downloading it on client.
--UPDATE--
I'm trying to use this solution, too.. is a good way?
res.writeHead(200, {"Content-Type": "application/pdf"});
res.write(data);
res.end();
Assuming you're using some sort of HTTP server here, you'll receive a response object in the handler. This object is actually a stream. I'm using the built-in node HTTP server here for my example.
http.createServer(function(req, res){
fs.createReadStream(path).pipe(res);
});
In express and hapi there is a specific send-file response type if you're using those:
Hapi: reply.file
Express: res.sendFile
I am using Gulp to develop an Angular application generated by Yeoman's gulp-angular generator. I have configured it to proxy requests to /api to another port, the port my API is listening on. That port is actually forwarded via an SSH tunnel to an external server.
Here is the config generated by Yeoman that I have edited for my own API:
gulp/server.js
'use strict';
var gulp = require('gulp');
var browserSync = require('browser-sync');
var httpProxy = require('http-proxy');
/* This configuration allow you to configure browser sync to proxy your backend */
var proxyTarget = 'http://localhost:3434/api'; // The location of your backend
var proxyApiPrefix = 'api'; // The element in the URL which differentiate between API request and static file request
var proxy = httpProxy.createProxyServer({
target: proxyTarget
});
function proxyMiddleware(req, res, next) {
if (req.url.indexOf(proxyApiPrefix) !== -1) {
proxy.web(req, res);
} else {
next();
}
// ...rest of config truncated
stdout
[BS] Watching files...
/Users/jason/dev/web/node_modules/http-proxy/lib/http-proxy/index.js:114
throw err;
^
Error: Parse Error
at Socket.socketOnData (http.js:1583:20)
at TCP.onread (net.js:527:27)
I get the above error when my application attempts to hit a particular API url which sends back a response of 204, no content.
url structure: POST /api/resource/delete
(API doesn't support actual DELETE http method so we POST to this endpoint)
Response: 204 No Content
The API is also in development and is being served via the built in PHP web server. What the server is telling us is that the client (aka Node in this case because it is the proxy) is hanging up before PHP can send the response.
I thought perhaps it was just choking on the fact that there was no content. So, we created a second endpoint that also returned 204 No Content and it seemed to work fine. But, to be fair, this issue appears to be intermittent - it works sometimes and sometimes it does not. It's very confusing.
As far as we can tell, it only happens on this delete URL, however. I am pretty new to Node and am having a very hard time figuring out what the issue is or where to look. Does anyone have any clues or has anyone seen this before?
It turns out that the developer of the API was sending me content along with his 204 when he shouldn't have been - some debug code left in. The HTTP parser that node-proxy uses was then reading that content from the buffer at the beginning of the subsequent request and then throwing an error because it wasn't seeing a properly formed HTTP request - since the first thing in the buffer was a PHP var_dump.
As it happens, my front end app did the delete call and then refreshes another object via the GET request. They happen so fast that it seemed like the DELETE call killed the gulp server, when it was actually the GET command afterwards.
The http-proxy module for node explicitly does not do error handling, leaving the onus on the end user. If you don't handle an error, it bubbles up into an uncaught exception and will cause the application to close, as I was seeing.
So, the fix was simply:
gulp/server.js
var proxy = httpProxy.createProxyServer({
target: proxyTarget
}).on('error', function(e) {
console.log(JSON.stringify(e, null, ' '))
});
The console will now log all proxy errors, but the process won't die and subsequent requests will continue to be served as expected.
For the error in question, the console output is:
{
"bytesParsed": 191,
"code": "HPE_INVALID_CONSTANT"
}
Additionally, we've fixed the API to honor its 204 and actually, you know, not send content.
This is really weird problem. I just installed Node.JS on my system (Fedora).
I have three files in /var/www/mirror/:
server.js
client.js
index.html
File server.js is the one I call via CLI: node server.js.
It, basically, returns index.html.
var
http = require('http'),
io = require('socket.io'),
fs = require('fs');
http.createServer(function(request, response) {
fs.readFile(__dirname + '/index.html', function(error, data) {
if (error) {
result.writeHead(500);
console.log('Error: Could not read index.html.');
}
response.writeHead(200, {'Content-Type': 'text/html'});
response.end(data);
});
}).listen(1337, '127.0.0.1');
console.log('Server is running.');
All works as expected and no errors are thrown anywhere.
In index.html I have simple HTML5 structure (nothing unnecessary, really!) and <script /> that points to, already mentioned, client.js.
That line of code looks like this (Ctrl + U; from browser):
<script src="client.js"></script>
By moving cursor on client.js, I got actual location: http://127.0.0.1:1337/client.js.
Seems correct, right?
The problem:
By opening that link it opens wanted file, but the content is as server.js should return.
This disallows me from including any internal scripts and style-sheets!
I guess that anything that goes via http://127.0.0.1:1337/ (also http://127.0.0.1:1337/client.js, http://127.0.0.1:1337/a/b/c etc.) is handled via server.js - and server.js returns index.html (see above).
How can I fix it? Thanks in any advice!
Look at the req.url to tell you the url that the user is requesting. From there, you have to have some code decide whether to serve index.html or client.js.
Also, since I'm guessing index.html isn't changing very frequently, you should probably just read it once, and store the buffer in a variable, rather than reading it on every request.
There are some modules that make serving static files a bit easier. Check out filed for a pretty nice standalone static file