I am creating a sveltejs/sapper app. I am trying to post some info from the frontend to the backend express server using axios in the script tag. Although get requests from external sources are succeeding, axios is throwing a 404 error while posting to the express route. Refer these images posted below.
server.js
const express = require('express');
const bodyParser = require('body-parser');
const fs = require('fs');
import sirv from 'sirv';
import * as sapper from '#sapper/server';
const app = express();
const { PORT, NODE_ENV } = process.env;
const dev = NODE_ENV === 'development';
app.use(
sirv('static', {dev}),
sapper.middleware(),
bodyParser.json(),
bodyParser.urlencoded({extended:true})
);
app.post('/task', (req, res) => {
res.sendStatus(200);
console.log(req.body);
// fs.writeFile(`./downloads/${req.body.file}`, req.body.buffer, (err) => {
// if (err) throw err;
// console.log(`${res.file} downloaded to backend server`);
// });
});
app.listen(PORT, err => {
if (err) console.log('error', err);
});
frontend script
<script>
//variables
let start = false;
let url = '';
let filename = '';
let downloadProgress = 0;
let error = false;
let progressBarStyle = 'bg-success';
//automated Events
$:downloadLabel = downloadProgress.toString();
$:if(downloadLabel == '100') {
progressBarStyle = 'bg-warning';
downloadLabel = 'DOWNLOAD COMPLETE! FILE WILL BE TRANSFERED SHORTLY!';
}
//axios config
let config = {
onDownloadProgress: progressEvent => {
downloadProgress = Math.floor((progressEvent.loaded * 100) / progressEvent.total); }
}
//functions
function startDownload() {
start = true;
axios.get(url, config).then((res) => {
if(res.status == 200) {
let data = {
file: filename,
buffer: res.data
}
axios.post('/task', data).then(() => {
console.log('Data sent to server');
}).catch((err) => {
console.log(err);
});
}
else {
error = true;
}
}).catch((err) => {
error = true;
});
}
function reset() {
// start = false;
// url = '';
// filename = '';
// downloadProgress = 0;
window.location.reload();
}
</script>
browser console
network tab
You use sapper,
Try to read docs.
example:
const express = require('express');
import sirv from 'sirv';
import compression from 'compression';
import * as sapper from '#sapper/server';
const { PORT, NODE_ENV } = process.env;
const dev = NODE_ENV === 'development';
const app = express();
app
/* add your handlers here */
.post('/task', (req, res, next) => {
res.sendStatus(200);
console.log(req.body);
})
.use(
compression({ threshold: 0 }),
sirv('static', { dev }),
sapper.middleware()
)
.listen(PORT, err => {
if (err) console.log('error', err);
});
I find here solution
You have to send something in the request handler:
(req, res) => {
res.sendStatus(200);
}
Related
The server is running and getting a lot of request while this route is not working all the other routes are working.
I am picking up error 404 with the following message.
my route works and after a while stops to work I don't know why and how this happens.
code example:
/images route
/**
* Root route, all validation will be done here.
* TODO:
*/
const { insertImgs,getExisting,getImg } = require('../core/DB.js');
const logger = require( '../logger/logger.js' ).getInstance();
class Images {
constructor(expressApp) {
if (!expressApp) throw 'no express app';
this.router = expressApp;
this.configure();
}
configure() {
this.router.get('/images',async (req, res, next) => {
try {
let images = await getImg(res.locals.config.siteConfig.ID, res.locals.config.siteConfig.ocrLicense)
/* merge results. */
return res.status(200).send( images );
} catch (err) {
/* log error */
console.log( 'alts failed', err );
logger.error({
type : 'req denied',
route : 'alts',
ip,
key : req.body.key,
data : req.body,
error : err
});
return res.status(503).send('Server Maintenance.');
}
});
return this.app;
}
}
module.exports = {
Images : Images
}
main.js
const express = require( "express" );
const cors = require( "cors" );
const http = require( 'http' );
const config = require( './config.js' );
const helmet = require("helmet");
/* routes */
const { Root } = require('./routes/root.js');
const { Alt } = require('./routes/alts.js');
const { Images } = require('./routes/images.js');
const { Health } = require('./routes/health.js');
const logger = require('./logger/logger.js').getInstance();
const app = express();
const server = http.createServer(app);
const port = config.port || 3003;
app.use( express.json() );
app.use( express.urlencoded( { extended: true } ) );
app.use( cors() );
app.use( helmet() );
/**
* init routes.
*/
[
Root,
Images,
Alt,
Health
].forEach(route => {
new route(app)
});
//404 last handler
app.use((req, res, next)=> {
res.status(404).send({error: 'Page not found'});
});
// error handler
app.use(function(err, req, res, next) {
// render the error page
res.status(err.status || 500);
res.send('error 404');
});
server.listen(port,()=>{
logger.log({ type : `server startup in process : ${ process.pid }` , port : port });
});
i would guess that it has to do with the fact that you are using the http module in conjunction with express.
i also wouldn't wrap each route in an object, express provides a Router class to do exactly that:
i rewrote some parts of your code to be a bit more concise:
main.js
const express = require("express")
const cors = require("cors")
const helmet = require("helmet")
const config = require('./config.js')
const logger = require('./logger/logger.js').getInstance()
const images_route = require('./routes/images.js')
const app = express()
const port = config.port || 3003
function page_not_found(req, res, next) {
return res.status(404).send({
error: 'Page not found'
})
}
function error_handler(err, req, res, next) {
res.status(err.status || 500)
return res.send('error 404')
}
app.use(
express.json(),
express.urlencoded({ extended: true }),
cors(),
helmet()
)
app.use('/images', image_route)
app.use(error_handler)
app.all('/', page_not_found)
app.listen(port, () => {
logger.log({
type: `server startup in process : ${ process.pid }`,
port: port
})
});
images.js
const express = require('express')
const route = express.Router()
const { insertImgs, getExisting, getImg } = require('../core/DB.js')
const logger = require('../logger/logger.js').getInstance()
route.get('/', async (req, res, next) => {
try {
let images = await getImg(
res.locals.config.siteConfig.ID,
res.locals.config.siteConfig.ocrLicense
)
return res
.status(200)
.send( images )
} catch (err) {
console.error('alts failed', err)
logger.error({
type: 'req denied',
route: 'alts',
ip,
key: req.body.key,
data: req.body,
error: err
})
return res
.status(503)
.send('Server Maintenance');
}
})
module.exports = route
it is much easier to see what routes are being used from your main.js file now, this makes it harder to have overlapping endpoints.
let me know if this helps at all.
try/catch does not work with async code. You also should not be using await inside a route handler as doing so may prevent other requests from getting processed.
Instead of this code:
this.router.get('/images',async (req, res, next) => {
try {
let images = await getImg(res.locals.config.siteConfig.ID, res.locals.config.siteConfig.ocrLicense)
/* merge results. */
return res.status(200).send( images );
} catch (err) {
/* log error */
console.log( 'alts failed', err );
logger.error({
type : 'req denied',
route : 'alts',
ip,
key : req.body.key,
data : req.body,
error : err
});
return res.status(503).send('Server Maintenance.');
}
});
Try this modified version:
this.router.get('/images', (req, res) => {
getImg(
res.locals.config.siteConfig.ID,
res.locals.config.siteConfig.ocrLicense
).then(images => {
res.status(200).send(images);
}).catch(err => {
console.log('alts failed', err);
logger.error({
type : 'req denied',
route : 'alts',
ip,
key : req.body.key,
data : req.body,
error : err
});
res.status(503).send('Server Maintenance.');
});
});
This assumes that getImg is either declared as an async function or returns a Promise.
I am trying to follow along a tutorial and use nodejs with 'gridfs-stream' along with a react front end. The tutorial is from last year in 2020.
Here is my code.
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const cors = require('cors')
const multer = require('multer');
const {GridFsStorage} = require('multer-gridfs-storage');
const Grid = require('gridfs-stream');
const path = require('path');
const Pusher = require('pusher')
const mongoPosts = require ('./mongoPosts.js')
// const currentTournamentControllers = require('../controllers/currenttournament-controllers');
const app = express();
const port = process.env.PORT || 9000
app.use(bodyParser.json())
app.use(cors())
const mongoURI = 'mongodb+srv://fbclient:rmbmbkvZVHw3e6OK#cluster0.emaw1.mongodb.net/myFirstDatabase?retryWrites=true&w=majority'
const conn = mongoose.createConnection(mongoURI);
mongoose.connect(mongoURI)
mongoose.connection.once('open', () => {
console.log('DB Connected')
})
let gfs
conn.once('open', () => {
// Init stream
gfs = Grid(conn.db, mongoose.mongo);
gfs.collection('images');
});
const storage = new GridFsStorage({
url: mongoURI,
file: (req, file) => {
return new Promise((resolve, reject) => {{
const filename = `image-${Date.now()}${path.extname(file.originalname)}`
const fileInfo = {
filename: filename,
bucketName: 'images'
}
resolve (fileInfo)
}})
}
})
const upload = multer({storage})
app.get('/', (req, res) => res.status(200).send('hello world'))
app.post('/upload/image', upload.single('file'), (req, res) => {
res.status(201).send(req.file)
})
app.post('/upload/post', (req, res) => {
const dbPost = req.body
console.log(dbPost)
mongoPosts.create(dbPost, (err, data) => {
if(err){
res.status(500).send(err)
} else {
res.status(201).send(data)
}
})
})
app.get('/retrieve/image/single', (req, res) => {
console.log(req.query.name)
gfs.files.findOne({filename: req.query.name}, (err, file) => {
if(err) {
res.status(500).send(err)
} else {
console.log(file)
if(!file || file.length === 0) {
console.log("hi i errored out")
res.status(404).json({err: 'file not found'})
} else {
console.log("hi i am trying to read")
const readstream = gfs.createReadStream(file.filename)
readstream.pipe(res)
}
}
})
})
app.get('/retrieve/posts', (req, res) => {
mongoPosts.find((err, data) => {
if(err){
res.status(500).send(err)
} else {
data.sort((b,a) => {
return a.timestamp - b.timestamp
})
res.status(200).send(data)
}
})
})
app.listen(port, () => console.log(`listening on localhost:${port}`))
The problem is with readstream. When I am trying to retrieve the data it shows the error
TypeError: grid.mongo.ObjectID is not a constructor
I did some debugging and figured out that this can be fixed by changing a value inside the gridfs.js file in the node_modules. The change being suggested on Stack Overflow was this :-
this._store = new grid.mongo.GridStore(grid.db, this.id || new grid.mongo.ObjectID(), this.name, this.mode, options);
changed to
this._store = new grid.mongo.GridStore(grid.db, this.id || new grid.mongo.ObjectId(), this.name, this.mode, options);
The suggestion was to change the grid.mongo.ObjectID value to grid.mongo.ObjectId. So I did that. Now the error coming out is as follows:-
TypeError: grid.mongo.GridStore is not a constructor
For this I am not getting any fixes on stack overflow or any other websites. Can someone please help
With the following code Im trying to create a accessToken with the simple-oauth2 library in node.
I have the server.js and the app.js files. The problem is that every time I try to call the getToken method it returns the following error The content-type is not JSON compatible. Im calling the /token endpoint with postman where the request´s Content-Type is set to application/json.
Has anyone encountered this problem before?
server.js
'use strict';
const app = require('express')()
const bodyParser = require('body-parser')
app.use(bodyParser.json())
const port = 3000;
module.exports = (cb) => {
app.listen(port, (err) => {
if (err) return console.error(err);
console.log(`Express server listening at http://localhost:${port}`);
return cb({
app
});
});
};
app.js
const createApplication = require('./server');
const simpleOauthModule = require('simple-oauth2');
require('dotenv').config()
const credentials = {
client: {
id: process.env.CLIENT_ID,
secret: process.env.CLIENT_SECRET
},
auth: {
tokenHost: 'http://localhost:3000/test'
}
};
createApplication(({ app }) => {
app.post('/token', async (req, res) => {
const oauth2 = simpleOauthModule.create(credentials);
var contype = req.headers['content-type']; // <-- application/json
const tokenConfig = {
username: "test",
password: "1234"
};
try {
const result = await oauth2.ownerPassword.getToken(tokenConfig); //Error occuress
const accessToken = oauth2.accessToken.create(result);
console.log('Access Token: ', accessToken);
} catch (error) {
console.log('Access Token Error', error.message);
}
});
app.post('/test', async (req, res) => {
});
});
I have a working codebase where they have already setup node proxy and jwt.
my server is running at 1010 port
but when I hit this url http://localhost:1010/sampletest
I am getting an error in the browser screen Cannot GET /sampletest
even I hit this url http://localhost:1010/jump/api/v1 but still I am getting same error
can you tell me how to fix it or am I missing anthing in the configurations
providing my index.js and server.js code below
sports.js
const express = require('express');
const axios = require('axios');
const mime = require('mime-types');
const router = express.Router();
const ResponseUtil = require('../../utils/ResponseUtil');
const AppConstants = require('../../../constants/AppConstants');
const credentials = require('../../../internals/credentials.json');
const memberGroupingHelper = require('../../helpers/rank/memberGrouping');
const exportHelper = require('../../helpers/rank/rankExportHelper');
const formatExportData = require('../../helpers/rank/formatExportData');
const rankCommonHelper = require('../../helpers/rank/rankCommonHelper');
const rankProvDataHelper = require('../../helpers/group/getProvData');
//const aggregateHelper = require('../../helpers/group/aggregateFilter');
const { rankAggregatelastrsApi } = require('jump-svc-utils');
//router.get('/:searchMode/:lastrSearch', (req, res, next) => {
router.get('/sampletest', (req, res, next) => {
const { originalUrl } = req;
//console.log(" originalUrl ", originalUrl);
const mode = req.params.searchMode;
const value = encodeURIComponent(req.params.lastrSearch);
console.log("document 40--->", mode);
console.log("for document Testing0--->", mode);
const url = `/jkjkjk/sdjksdjkjksdjksd/sdklsdlksdklsdkl`;
axios.get(AppConstants.GET_JWT_TOKEN_URL, {
auth: {
username: credentials.auth.racfId, password: credentials.auth.password
}
})
.then((jwtResponse) => {
// var jwtToken = `Bearer ${jwtResponse.data.jwt}`;
var jwtToken = `Bearer 787878bjhbnmnmmwqdqwqwqwqwqwqwqwqwqwqwqwqwqwqwqwqwqwqw`;
axios.get(url, { headers: { "Authorization": jwtToken } })
.then((response) => {
console.log("document then0--->", response);
const file = Buffer.from(response.data.content, 'base64');
const fileType = mime.contentType(response.data.contentInfo.fileType);
const fileExtension = response.data.contentInfo.fileType.toLowerCase();
const fileName = `filename=${response.data.contentInfo.id}.${fileExtension}`;
res.set('Content-Type', fileType);
res.set('Content-disposition', `attachment; ${fileName}`);
res.send(file);
})
.catch((e) => {
console.log("e catch document0--->", e);
console.log("e.message catch document0--->", e.message);
console.log("catch document--->", e.response);
if (e.response) {
return res.status(e.response.status).send(e.response.data);
}
res.status(500).send(e.message || 'Something wrong');
});
});
ResponseUtil.callService(res, url);
});
module.exports = router;
index.js
const express = require('express')
const app = express()
const port = 1010
const jumpServices = require('./services/jump');
const compression = require('compression');
var BodyParser = require('body-parser');
const glob = require('glob');
const path = require('path');
app.use('/jump/api/v1', jumpServices);
app.use(BodyParser.json());
app.use(BodyParser.urlencoded({
extended: true
}));
//app.use(compress())
// app.use(compression());
// include all the controllers
const controllers = glob.sync(path.join(__dirname, '/controllers/**/*.js'));
console.log("controllers--->", controllers);
controllers.forEach((controllerFileName) => {
require(controllerFileName)(app); //eslint-disable-line
});
app.listen(port, (err) => {
if (err) {
return console.log('something bad happened', err)
}
console.log(`server is listening on ${port}`)
})
I don't see any calls registering your sub Routers with the top level express application. You should need to call app.use for each of your sub routers.
I send request from React with:
export const loadItems = () => async dispatch => {
await axios
.get("http://localhost:8000/api/users")
.then(response => {
console.log(response.users);
dispatch(dataLoaded(response.users));
})
.catch(err => {
dispatch(dataLoadFailed(err));
});
};
But there is no response, and the server does not take request, here is my server app code:
server.js
// a lot of requires
const todoRoutes = require("./routes/serverRoute");
const url = "mongodb://localhost:27017/taskManager";
const app = express();
mongoose.Promise = global.Promise;
mongoose.connect(
url,
{ useNewUrlParser: true },
function(err) {
if (err) {
console.log(err);
} else console.log("Database connected");
}
);
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "/public/index.html"));
});
// cors allow
app.use("/api", todoRoutes);
app.listen(8000, () => {
console.log("API started");
});
And this is a controller I use, it's all good with Schema and DB, I checked with output to console from the node, users is defined and contains data
const mongoose = require("mongoose");
const User = require("../models/UserModel");
module.exports = {
getUsers(req, res) {
User.find().exec((err, users) => {
if (err) {
console.log(err);
return res.send({ err });
} else {
console.log(users);
return res.send({ users });
}
});
}
};
And this is my router:
module.exports = router => {
router.get('/users', userController.getUsers);
}
Ok, I got it on my own. Problem was here:
router.get('/users', userController.getUsers);
It supposed to be like this:
router.get('/users', userController.getUsers());