I am trying to develop an API that allow POST request of file data, but the POST request only functions using curl curl -X POST --data file= mouse.fa "http://localhost:3000/api/data?file=mouse.fa" . When I trying a POST request in the browser, I get a GET error Cannot GET /api/data. Please could you advise me on how to get the POST request to work in the browser in addition to curl.
router.js
const fs = require('fs');
const express = require('express');
const bodyParser = require('body-parser');
fileParser = require("./fileParser")
router.use('./fileParser', fileParser.parse);
// middleware
router.use(function (req, res, next) {
console.log('Received request');
next();
});
router.post('/data', function (req, res) {
//Check file is valid
if (!req.body.file.toString().endsWith('.fa')) {
res.status(400).json({ message: "Bad Request" });
} else {
fileParser.parse(`./${req.body.file.toString()}`);
res.json({ message: "File parsed and data submitted.", location: "/data/" });
}
});
server.js
const express = require('express');
// create server
const app = express();
const port = 3000;
app.listen(port, function () {
console.log(`Server running at ${port}`)
});
// import router
const router = require('./router');
app.use('/api', router)
Related
I am trying to make Postman work with React JS using express. I am following a Mern Stack Development tutorial in free code camp. I have Cors extension enabled in my browsers, both in Chrome and in Edge. I keep getting this message in localhost:5000 "Cannot get /" and get this message {"msg":"This is CORS-enabled for an allowed domain."} in localhost:5000/users/add. My code looks something like this:
This is my server.js
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
require('dotenv').config();
const app = express();
const port = process.env.PORT || 5000;
app.use(cors());
app.use(express.json());
const uri = process.env.ATLAS_URI;
mongoose.connect(uri,{useNewUrlParser: true, useCreateIndex:true, useUnifiedTopology:true});
const connection= mongoose.connection;
connection.once('open', () =>{
console.log("Mongodb database connection established successfully");
})
const exercisesRouter= require('./routes/exercises');
const usersRouter= require('./routes/users');
var allowlist = ['http://localhost:5000']
var corsOptionsDelegate = function (req, callback) {
var corsOptions;
if (allowlist.indexOf(req.header('Origin')) !== -1) {
corsOptions = { origin: true } // reflect (enable) the requested origin in the CORS response
} else {
corsOptions = { origin: false } // disable CORS for this request
}
callback(null, corsOptions) // callback expects two parameters: error and options
}
app.use('./exercises',exercisesRouter);
app.use('./users', usersRouter);
app.get('/users/add', cors(corsOptionsDelegate), function (req, res, next) {
res.json({msg: 'This is CORS-enabled for an allowed domain.'})
})
app.listen(port, ()=>{
console.log(`Server is running on port: ${port}`);
});
app.listen(80, function () {
console.log('CORS-enabled web server listening on port 80')
})
cords don’t have anything to do with this
Can you tell me where is yow route for “/“ something like this
app.get(“/“, (req,res)=>{
…..
});
Yes exactly. You don’t have it. If the route/endPoint is not declared how do use expect them browsers to show you some else
When browssers open yow link at localhost:5000
They make a get request to “/“. So express just tell’em
Can not get “/“
I do not
I want to download zip file by response using Node.js and express. I could downloaded it but it coruppted. I made 2 servers, one is for data storing and the other is front-end. I can't put the zip file on front-end server so I need to get it by response. following is the code:
for frontend (front-end-server)
const express = require("express");
const app = express();
const http = require('http');
const server = http.createServer(app);
const request = require('request');
app.get("/api/download", (req, res) => {
request('http://192.168.10.888:8088/getfile', (error, response, body) =>
{
res.set({
'Content-Type': 'application/zip',
'Content-Disposition': 'attachment; filename="sample.zip"'
});
res.send(body);
});
});
app.get('/', (req, res) => res.send('Hello app'));
app.listen(8081, () => console.log('Listening on port 8081'));
for data storing (data-server)
var fs = require('fs');
var http = require('http');
const express = require("express");
const app = express();
app.get('/getfile', function (req, res)
{
res.sendFile("/data/sample.zip");
});
app.get('/', (req, res) => res.send('Hello'));
app.listen(8088, () => console.log('Listening on port 8088'));
data-server just return the file as stream and front-end-server get it by http-request and return it to browser so I expected download the zip file by simply type following URL
http://192.168.10.97:8081/api/download
I am using Groovy script to perform HTTP POST request with some data:
import groovyx.net.http.HTTPBuilder
import static groovyx.net.http.ContentType.*
import groovyx.net.http.ContentType
import static groovyx.net.http.Method.*
def http = new HTTPBuilder('myhost.com')
http.request( POST ) {
uri.path = '/'
requestContentType = ContentType.JSON
body = [title: 'some data', desc: 'some more data']
log.info(body.title)
response.success = { resp,reader ->
log.info( "POST response status: "+resp.statusLine+"}")
}
}
This works just fine, Groovy results are below:
Logs:
INFO : some data
INFO : POST response status: HTTP/1.1 200 OK}
But when I see my web service logs the request body is undefined:
Here's the code:
const express = require('express');
const app = express();
var test = {0:'post'};
app.get('/', (req, res) => {
res.send('a');
console.log('request inbound');
});
app.post('/',(req,res) => {
res.send('test');
console.log('post in');
console.log(req.body);
});
// Listen to the App Engine-specified port, or 8080 otherwise
const PORT = process.env.PORT || 30000;
app.listen(PORT, () => {
console.log(`Server listening on port ${PORT}...`);
});
I'm using Node.js v12.13 | npm v6.12 | express.js 4.17.1
I'm afraid you've omitted app.use(express.json()).
const express = require('express');
const app = express();
app.use(express.json())
var test = {0:'post'};
app.get('/', (req, res) => {
res.send('a');
console.log('request inbound');
});
...
I'm trying to set a cookie with a post method in order to do some db query and put it back in the cookie value, as well as returning a json with the user data.
It works, the cookie is set and I get the json on http://localhost:8080
but I get a message from the compiler:
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
How can I fix it so it won’t make this error?
my file structure is:
root/ app.js
root/controllers/ cookie.controller.js
root/routes/ cookie.route.js
app.js
const express = require('express');
const cors = require('cors');
const cookieParser = require('cookie-parser');
const app = express();
const port = process.env.PORT || process.argv[2] || 8080;
app.use(cookieParser());
app.use(require('./routes/cookies'));
app.use(cors());
app.listen(port, () => console.log('cookie-parser demo is up on port: ' + port));
cookie.route.js
const express = require('express');
const cookieController = require('../controllers/cookies');
const router = express.Router();
router.use(require('cookie-parser')());
router.post('/', router.use(cookieController.getCookie));
module.exports = router;
cookie.controller.js
exports.getCookie = (req, res, next) => {
let auth = req.cookies.auth;
//...db queries, get userData
let userData = {
id: '123',
token: 'sfsdfs34',
email: 'user#gmail.com'
};
// if cookie doesn't exist, create it
if (!auth) {
res.status(200)
.cookie('auth', userData.id)
.json({ message: 'it works!', user: userData });
req.cookies.auth = userData.id;
}
next();
};
You're modifying the request cookie headers after sending the response at the end of your getCookie controller. You should remove req.cookies.auth = userData.id, and use res.cookie() instead before sending the response.
const express = require('express')
const cookieParser = require('cookie-parser')
const app = express()
app.use(cookieParser())
app.get('/', (req, res) => {
if (!req.cookies.auth) {
res.cookie('auth', { id: '123' })
}
res.json({ message: 'It worked!' })
})
app.listen(8080, () => console.log('http://localhost:8080))
Problem was solved after deleting the cors from app.js
I'll try to make this as to the point as possible. I am trying to make a post request to my express backend. All of the post requests here work, except for "/addpayment". Here is my file called 'router.js'
module.exports = function(app) {
app.post('/signin', requireSignin, Authentication.signin)
app.post('/signup', Authentication.signup)
app.post('/addpayment', function(req, res, next) {
res.send({ message: 'why................' })
})
}
Here is my main 'server.js' file
const express = require('express')
const http = require('http')
const bodyParser = require('body-parser')
const morgan = require('morgan')
const app = express()
const router = require('./router')
const mongoose = require('mongoose')
const cors = require('cors')
// DB Connect
mongoose.connect('mongodb://localhost/demo-app')
// App
app.use(morgan('combined'))
app.use(cors())
app.use(bodyParser.json({ type: '*/*' }))
router(app)
// Server
const port = process.env.PORT || 3090
const server = http.createServer(app)
server.listen(port)
console.log('Server has been started, and is listening on port: ' + port)
I get a 404 in postman, and inside my app browser console. I am using passport in my other routes. I already tried running it through passport when I have a JWT token, and same thing(a 404).
I have already looked at all Stack Overflow/Github posts on the first few pages of google results, with no solution for my use case.
I have made a simplified version of your server and everything works as expected. Only difference that I have made is that I am not creating http server like you, but just calling app.listen
here is working example
router.js
module.exports = function(app) {
app.post('/addpayment', function(req, res, next) {
res.send({message: 'why................'})
})
};
server.js
var express = require('express');
var router = require('./router');
var app = express();
router(app);
//init server
app.listen(3000, function() {
console.log("Server running on port 3000");
});