Connect Server: Mod_Rewrite - Uncaught SyntaxError: Unexpected token < - javascript

I have a Gruntfile, which setups a Connect Server, and I'm trying to add mod_rewrite module (https://www.npmjs.com/package/connect-modrewrite) to add some rules.
Basically, What I need to do, is to add a rewrite for all '^/invite/(.*)$ to the root of my site.
For that I have this config in my Gruntfile.js:
...
middleware: function (connect) {
var middlewares = [];
middlewares.push(modRewrite(['^/invite/(.*)$ / [L]']));
middlewares.push(connect.static(appConfig.app))
return middlewares;
}
...
The route seems to work, since if I check on the inspector, the html of the root page is there.
However, I get this message:
(index):1 Uncaught SyntaxError: Unexpected token <
What is wrong?
EDIT
Errors:

Related

JSON Web Tokens Node JS Server ERROR SyntaxError: Unexpected token } in JSON at position 24

Me and others are experiencing this error: SyntaxError: Unexpected token } in JSON at position 24 at JSON.parse (<anonymous>) while following this tutorial on JSON Web Tokens (LINK: https://www.youtube.com/watch?v=mbsmsi7l3r4&t=34s, around minute: 10:00)
The error appears during this POST request:
Content-Type: application/json
{
"username": "Kyle",
}
You can find the full code up to that point here:
https://github.com/emanuelefavero/json-web-tokens
There are 3 main files to watch for:
server.js
.env (I left the .env file in the github repository)
request.rest (I used this file to make POST request but you can use POSTMAN or other methods)
The error seems to be in server.js, specifically in the express-JWT method:
app.post('/login', (req, res) => {
// Authenticate User
// Create json web token
const username = req.body.username
const user = { name: username }
const accessToken = jwt.sign(user, process.env.ACCESS_TOKEN_SECRET)
console.log(accessToken)
res.json({ accessToken: accessToken })
})
The GET request is working fine.
While I'm trying to fix this error I'll still respond to any questions and provide project details if needed. Thank you.
Full Error Message:
SyntaxError: Unexpected token } in JSON at position 24
at JSON.parse (<anonymous>)
at parse (/Users/arch0n/Desktop/JWT/json-web-token/node_modules/body-parser/lib/types/json.js:89:19)
at /Users/arch0n/Desktop/JWT/json-web-token/node_modules/body-parser/lib/read.js:128:18
at AsyncResource.runInAsyncScope (node:async_hooks:199:9)
at invokeCallback (/Users/arch0n/Desktop/JWT/json-web-token/node_modules/raw-body/index.js:231:16)
at done (/Users/arch0n/Desktop/JWT/json-web-token/node_modules/raw-body/index.js:220:7)
at IncomingMessage.onEnd (/Users/arch0n/Desktop/JWT/json-web-token/node_modules/raw-body/index.js:280:7)
at IncomingMessage.emit (node:events:402:35)
at endReadableNT (node:internal/streams/readable:1343:12)
at processTicksAndRejections (node:internal/process/task_queues:83:21)
It appears the issue lies in the request you're making. You have a trailing comma in the JSON that you are sending in your request.
If you are new to using JSON & JavaScript, just try to remember that JavaScript objects !== JSON.
In JS Objects, you can have trailing commas. However, in JSON it will cause issues.

Is it possible to run Nodemailer on client only (using React) without a backend? [duplicate]

I've created a simple react redux app (using webpack) with a contact form which when the user clicks submit I want to generate and send an email. To do this I have been trying to use nodemailer like so:
import nodemailer from 'nodemailer';
//...
sendEmail () {
const emailInfo = {
to: 'foo#bar.com',
from: 'bar#foo.com',
subject: 'Message from bar',
text: 'Hello world!'
};
const connectionInfo = {
host: '...',
port: 123,
secure: true,
auth: {
user: 'foo#bar.com',
pass: 'foo123'
}
};
const transporter = nodemailer.createTransport('SMTP', connectionInfo);
transporter.sendMail(emailInfo, function(error){
if(error){ console.log('error'); }
console.log('sent');
});
}
... however I've been getting a lot of errors to do with the nodemailer import.
ERROR in ./~/nodemailer/package.json
Module parse failed: /Users/myUser/website/node_modules/nodemailer/package.json Unexpected token (2:8)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token (2:8)
ERROR in ./~/nodemailer/lib/http-proxy.js
Module not found: Error: Cannot resolve module 'net' in /Users/myUser/website/node_modules/nodemailer/lib
# ./~/nodemailer/lib/http-proxy.js 7:10-24
ERROR in ./~/nodemailer/lib/http-proxy.js
Module not found: Error: Cannot resolve module 'tls' in /Users/myUser/website/node_modules/nodemailer/lib
# ./~/nodemailer/lib/http-proxy.js 8:10-24
ERROR in ./~/nodemailer/~/nodemailer-direct-transport/lib/direct-transport.js
Module not found: Error: Cannot resolve module 'dns' in /Users/myUser/website/node_modules/nodemailer/node_modules/nodemailer-direct-transport/lib
# ./~/nodemailer/~/nodemailer-direct-transport/lib/direct-transport.js 5:10-24
ERROR in ./~/nodemailer/~/nodemailer-direct-transport/lib/direct-transport.js
Module not found: Error: Cannot resolve module 'net' in /Users/myUser/website/node_modules/nodemailer/node_modules/nodemailer-direct-transport/lib
# ./~/nodemailer/~/nodemailer-direct-transport/lib/direct-transport.js 6:10-24
ERROR in ./~/nodemailer/~/nodemailer-direct-transport/package.json
Module parse failed: /Users/myUser/website/node_modules/nodemailer/node_modules/nodemailer-direct-transport/package.json Unexpected token (2:8)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token (2:8)
Am I missing something here or is nodemailer simply not designed for use in the browser? If that's the case is there another option I should be looking at?
node.js is for server side JavaScript, and allows you to do many things that can't be done in a browser.
Sending email is not something that can be done in the sandbox provided by a browser, beyond the limited capabilities of mailto links which can basically pop up the user's email client with some links filled in.
You need to implement server side code to do this, triggered by some action from the client, which could be node.js and nodemailer.

error: (-215) !empty() in function detectMultiScale in Opencv.JS

I have checked and tried these solutions here but none is helping
error: (-215) !empty() in function detectMultiScale
OpenCV.js - detectMultiScale "This Exception cannot be caught"
I also read elsewhere that the problem could be because the file needs to be served via an Http request and so I decided to use ngrok but I still found the same error. Currently am using python http.server
Here is the section of the code:
let classifier = new cv.CascadeClassifier();
let utils = new Utils('errorMessage'); //use utils class
let faceCascadeFile = "http://localhost:8000/docs/haarcascade_frontalface_default.xml";
//let faceCascadeFile = "D:\Code\Fit-to-Interact-web\docs\haarcascade_frontalface_default.xml"
//let faceCascadeFile = "https://0979da552cb5.ngrok.io/docs/haarcascade_frontalface_default.xml"; // path to xml
// use createFileFromUrl to "pre-build" the xml
//Make sure to run it in a webserver because it has to do XMLHTTPRequests.
utils.createFileFromUrl(faceCascadeFile, faceCascadeFile, () => {
classifier.load(faceCascadeFile); // in the callback, load the cascade from file
});
console.log(classifier.empty())
Worse when I use the absolute/relative file path I get this error Not allowed to load local resource or sometimes the same error:
Exception: OpenCV(4.4.0) /build/master-contrib_docs-lin64/opencv/modules/objdetect/src/cascadedetect.cpp:1689:
error: (-215:Assertion failed) !empty() in function 'detectMultiScale'

ModuleParse Failed or Not Found

I am building a web app that allows users to type in phone numbers and send text messages via the Twilio API. I've built the functionality in a file, shown below. If I cd to this file and run node twilioActions.js, the text message gets sent.
var client = require('twilio')(CLIENT_ID, CLIENT_SECRET);
// ideally, I'd like to send the message using this method and call this from other JavaScript files
export const sendMessage = () => {
}
// the following code works when I run 'node twilioActions.js'
client.sendMessage({
to:'...',
from: '...',
body: 'Text message test.'
}, function(err, responseData) {
if (!err) {
console.log(responseData.from); // outputs "+14506667788"
console.log(responseData.body); // outputs "word to your mother."
}
});
However, I want to call the sendMessage method from a different React file. Here is it:
import * as twilioActions from './twilioActions';
class PhoneView extends React.Component{
// other methods are hidden obviously, the one below is called when a button is pressed to send a message.
sendMessage() {
twilioActions.sendMessage();
}
}
When I try to build the project, I get the following errors:
ERROR in ./~/twilio/package.json
Module parse failed:/Users/Felix/Desktop/ECE590/node_modules/twilio/package.json Line 2: Unexpected token :
You may need an appropriate loader to handle this file type.
| {
| "_args": [
| [
| "twilio",
# ./~/twilio/lib/Client.js 5:17-43
ERROR in ./~/request/lib/har.js
Module not found: Error: Cannot resolve module 'fs' in /Users/Felix/Desktop/ECE590/node_modules/request/lib
# ./~/request/lib/har.js 3:9-22
ERROR in ./~/tunnel-agent/index.js
Module not found: Error: Cannot resolve module 'net' in /Users/Felix/Desktop/ECE590/node_modules/tunnel-agent
# ./~/tunnel-agent/index.js 3:10-24
ERROR in ./~/tunnel-agent/index.js
Module not found: Error: Cannot resolve module 'tls' in /Users/Felix/Desktop/ECE590/node_modules/tunnel-agent
# ./~/tunnel-agent/index.js 4:10-24
I feel like I am making a simple mistake and perhaps am not using the correct libraries or including the proper references. Could someone point me in the right direction about how to get this to work? Thank you so much!
Twilio developer evangelist here.
The twilio npm module is not built or recommended for use in the front end. The main thing is that you would need to expose your account credentials in the front end code of your site. This is a security risk as it means a malicious attacker could get hold of your credentials and abuse your Twilio account.
I recommend creating a service on your server side that you can call to with an AJAX request in order to perform actions like this.

Node js + Sails js + websocket app crashing every few hours

I am having a problem similar to socket.io issue using sails.js. Every once in a while (once per day, or even few hours, it varies), a visitor to the web site/app will crash Node, seemingly due to the way his websocket client tries to connect. Anyway, here's the crash log:
debug: Lowering sails...
/Volumes/Two/Sites/lsdfinder/node_modules/sails/node_modules/express/node_modules/connect/lib/utils.js:216
return 0 == str.indexOf('s:')
^
TypeError: Cannot call method 'indexOf' of undefined
at exports.parseSignedCookie (/Volumes/Two/Sites/lsdfinder/node_modules/sails/node_modules/express/node_modules/connect/lib/utils.js:216:19)
at Manager.socketAttemptingToConnect (/Volumes/Two/Sites/lsdfinder/node_modules/sails/lib/hooks/sockets/authorization.js:35:26)
at Manager.authorize (/Volumes/Two/Sites/lsdfinder/node_modules/sails/node_modules/socket.io/lib/manager.js:910:31)
at Manager.handleHandshake (/Volumes/Two/Sites/lsdfinder/node_modules/sails/node_modules/socket.io/lib/manager.js:786:8)
at Manager.handleRequest (/Volumes/Two/Sites/lsdfinder/node_modules/sails/node_modules/socket.io/lib/manager.js:593:12)
at Server.<anonymous> (/Volumes/Two/Sites/lsdfinder/node_modules/sails/node_modules/socket.io/lib/manager.js:119:10)
at Server.EventEmitter.emit (events.js:98:17)
at HTTPParser.parser.onIncoming (http.js:2076:12)
at HTTPParser.parserOnHeadersComplete [as onHeadersComplete] (http.js:120:23)
at Socket.socket.ondata (http.js:1966:22)
9 Oct 10:42:24 - [nodemon] app crashed - waiting for file changes before starting...
In config/sockets.js, authorization is set to true. Not sure what else to do, where to fix this. Any suggestions? I can read the Sails docs too, but this appears to be a problem in Express/Connect, no? Thanks.
...René
The problem is that once every so often, a client will connect that has no cookies. Sails.js is using util.parseSignedCookie() from Connect without checking for errors, and therefore an error is thrown. This is what it looks like in Sails:
if (handshake.headers.cookie) {
handshake.cookie = cookie.parse(handshake.headers.cookie);
handshake.sessionID = parseSignedCookie(handshake.cookie[sails.config.session.key], sails.config.session.secret);
}
If you take a look into the cookieParser() middleware of Connect, you can see error checking is required:
if (cookies) {
try {
req.cookies = cookie.parse(cookies);
if (secret) {
req.signedCookies = utils.parseSignedCookies(req.cookies, secret);
req.signedCookies = utils.parseJSONCookies(req.signedCookies);
}
req.cookies = utils.parseJSONCookies(req.cookies);
} catch (err) {
err.status = 400;
return next(err);
}
}
I've created a Gist here that fixes the problem, and will submit a pull request to Sails.js when I have the time. The Gist uses Connect's cookieParser() middleware to automatically handle errors. If you want to use this, modify this file in your modules folder:
node_modules/sails/lib/hooks/sockets/authorization.js
If you are doing a crossdomain request, you could turn off authorization.
In *site_dir/config/sockets.js* set authorization to false. One way of doing it. You can also call your api with something like this
bash
**http://localhost:1337?cookie=smokeybear**
Its is in the comments on the sockets.js file.

Categories

Resources