I am little bit confused and need some help.
I write an HTTP server using Node.js, and make an HTTP request from Vue.js to the HTTP server. Somehow it always return error like this:
Error: Request failed with status code 404
at FtD3.t.exports (createError.js:16)
at t.exports (settle.js:18)
at XMLHttpRequest.f.(:3010/anonymous function) (http://localhost:3010/static/js/vendor.1dc24385e2ad03071ff8.js:1312:88758)
It seems like url address don't correct cause error is 404 in browser. I check url address several times but did't notice something wrong. What I miss?
P.S. The main task to load file from remote sftp server from website. I use to that task ssh2-sftp-client library as backend side.
When user click the button, application run getFile function where we send post request to HTTP server.
Code inside Vue.js component:
getFile (fileName) {
axios.post('http://localhost:3010/csv', {file_name: fileName}, {headers: {'Authorization': this.token}}).then(response => {
console.log(response)
this.showAlert('You download file successfully.', 'is-success', 'is-top')
}).catch((error) => {
console.log(error)
this.showAlert(error, 'is-danger', 'is-bottom')
})
}
app.js:
const express = require('express');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const cors = require('cors');
const path = require('path');
const bodyParser = require('body-parser');
const csvRouter = require('./server/routes/csv')
const app = express();
app.use(cors());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, 'dist')));
app.use(express.urlencoded({extended: false}));
app.use(cookieParser());
app.use('/csv', csvRouter);
module.exports = app;
routers/csv.js:
const express = require('express')
const router = express.Router()
const csvControllers = require('../controllers/csv')
router.get('/', csvControllers.getFile)
module.exports = router
controllers/csv.js:
const request = require('request')
const queryString = require('query-string')
let Client = require('ssh2-sftp-client')
let sftp = new Client()
const config = require('../config')
exports.getFile = (req, res) => {
console.log(req) // In console I don't notice nothing.
let data = {
file_name: req.query.file_name
}
let options = {
method: 'port',
json: true,
header: {'Authorization': req.header.token},
url: `http://localhost:3010/csv?` + queryString.stringify(data)
}
request(options, (error, response) => {
console.log('Message') // In console I don't notice nothing.
if (response) {
sftp.connect(config.sftpServer).then(() => {
return sftp.get('/reports/' + data.file_name)
}).then((chunk) => {
console.log(chunk)
}).catch((err) => {
console.log(err)
})
} else {
response.status(500).send(error)
}
})
}
It seems that app.listen(port) is missing in your app.js file:
app.listen(3000)
https://expressjs.com/en/starter/hello-world.html
In controllers/csv.js you never send a response. You should have a res.send or res.render or res.json somewhere.
Related
I have a simple backend that I'd like to return a string of data whenever a POST request is made. The string is converted to JSON, but when I see that the response was successfully received by the client (the browser), the string is missing from the response data in the browser's console.
server.js (the request handler itself is simple, there's just a few dependencies listed)
const path = require('path');
const express = require('express');
const bp = require("body-parser");
const request = require("request");
const {createCanvas, loadImage} = require("canvas");
const cors = require('cors');
const requestIp = require('request-ip');
const { json } = require('body-parser');
const bodyParser = require('body-parser');
const wgServer = express();
const port = 3000;
const fs = require("fs");
const { createContext } = require("vm");
wgServer.use(cors())
wgServer.use(bp.json())
wgServer.use(bp.urlencoded({ extended: true }))
wgServer.use("/public", express.static(path.join(__dirname, 'public')));
wgServer.use(bodyParser.json({limit: '50mb'}))
wgServer.listen(port, function() {
console.log(`Weatherglyph server succesfully listening on port ${port}.`)
});
wgServer.post('/', async function (req, res) {
res.set('Content-Type', 'application/json');
... Lots of functions etc irrelevant to the question
let picpath = __dirname + "\\image.png";
let picbuff = fs.readFileSync(picpath);
let picbase64 = picbuff.toString('base64');
console.log(picbase64);
res.status(201).json({picbase64});
res.send();
})})
script.js
async function submitCity(){
let x = document.getElementById("wg_input").value;
console.log("Successfully captured city name:", x);
let toWeather = JSON.stringify({city: x});
console.log("Input data successfully converted to JSON string:", toWeather);
const options = {
method: 'POST',
mode: 'cors',
headers: {'Content-Type': 'application/json'},
body: toWeather
}
fetch('http://localhost:3000', options)
.then(res => console.log(res))
.catch(error => console.log(error))
}
Is the data (a .png converted to base64 and sent to the frontend) actually reaching the client and I just can't see it in Chrome's console, or am I sending it incorrectly?
Sorry if I don't post the correct details, this is my first hands-on project after going through online tutorials.
I'm using React, node with axios to build a web app that captures status(available, in a meeting, lunch etc) and the time spent on each status.
The app works fine, it captures and writes the data onto the backend(JSON) however, I keep getting this error on the console.
POST https://localhost:5000/write net::ERR_CONNECTION_RESET
Uncaught (in promise) ERROR: Network Error
I've tried to look for a solution but can't find one that is similar to the tech-stack I used. Also, my lack of sufficient knowledge don't help either.
Any lead or read or solution will help.
pasting my code below:
My frontend code to push data into JSON file
const saveJson = (posts) => {
//api URL //end point from node server / express server
const url = "http://localhost:5000/write";
axios.post(url, posts).then((response) => {
//console.log(response);
}); };
The server.js code
const express = require("express");
const bodyParser = require("body-parser");
//calling packages
const fs = require("fs");
const morgan = require("morgan");
const cors = require("cors");
//Declare app
const app = express();
const port = 5000;
//middlewares
app.use(bodyParser.json());
app.use(morgan("dev"));
app.use(cors());
//default route for server
app.get("/", (req, res) =>
res.status(200).send({
message: "Server is running...",
})
);
const WriteTextToFileAsync = async (contentToWrite) => {
fs.writeFile("./src/data.json", contentToWrite, (err) => {
console.log(contenToWrite);
if (err) {
console.log(err);
} else {
console.log("Done writing to file...");
// res.json({ msg: "success" });
}
});
};
//Declare timerow/write route to accept incoming require with data
app.post("/write", async (req, res, next) => {
//take the body from incoming requestby using req.body and conver it into string
const requestContent = JSON.stringify(req.body);
await WriteTextToFileAsync(requestContent);
});
//404 route for server
app.use((req, res, next) =>
res.status(404).send({
message: "Could not find specified route requested...!",
})
);
//run server
app.listen(port, () => {
console.log(
`!!! server is running
!!! Listening for incoming requests on port ${port}
!!! http://localhost:5000
`
);
});
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)
I am using a NextJS/MERN stack. My NextJS is using my server.js file, along with importing the routes for my API. The routes appear to be working as they do show activity when firing an API call from Postman or the browser. However, this is where the activity stops. It's not getting passed the Model.find() function as far as I can tell. I am not sure if this has to do with Next js and the prepare method in the server.js, or if this is related to the bodyparser issue.
Here is my server.js
const express = require("express");
const urlObject = require('./baseURL')
const passport = require("./nextexpress/config/passport-setup");
const passportSetup = require("./nextexpress/config/passport-setup");
const session = require("express-session");
const authRoutes = require("./nextexpress/routes/auth-routes");
const KBRoutes = require("./nextexpress/routes/kb-routes");
const userRoutes = require('./nextexpress/routes/user-routes')
const pollRoutes = require('./nextexpress/routes/poll-routes')
const mongoose = require("mongoose");
const cookieParser = require("cookie-parser"); // parse cookie header
const next = require('next')
const dev = process.env.NODE_ENV !== 'production'
const nextapp = next({ dev })
const handle = nextapp.getRequestHandler()
const bodyParser = require('body-parser');
// mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost:27017/kb', { useNewUrlParser: true });
mongoose.connect('mongodb://localhost:27017/kb')
console.log(process.env.MONGODB_URI)
const connection = mongoose.connection;
const baseURL = urlObject.baseURL
const PORT = process.env.PORT || 3000
connection.once('open', function () {
console.log("MongoDB database connection established successfully");
})
nextapp.prepare().then(() => {
const app = express();
console.log(process.env.PORT, '----port here ----')
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use("/api/auth", authRoutes);
app.use("/api/kb", KBRoutes);
app.use('/api/user', userRoutes)
app.use('/api/poll', pollRoutes)
app.get('/posts/:id', (req, res) => {
return nextapp.render(req, res, '/article', { id: req.params.id })
})
app.get('/redirect/:id', (req, res) => {
return nextapp.render(req, res, '/redirect')
})
app.all('*', (req, res) => {
return handle(req, res)
})
app.listen(PORT, err => {
if (err) throw err
console.log(`> Ready on http://localhost:${PORT}`)
})
})
// connect react to nodejs express server
And the relevant route:
KBRoutes.get('/', (req, res) => {
console.log(KB.Model)
KB.find({}, (err, photos) => {
res.json(kbs)
})
})
I am able to get to each one of the routes. Before this was working, when I had the NextJS React portion split into a separate domain therefore separate server.js files. Once I introduced NextJs thats when this problem arose. Any help would be greatly appreciated.
It looks like the relevant route is trying to return json(kbs), but kbs doesn't seem to be defined. Returning the result of your find query would make more sense to me, including a nice error catcher and some status for good practice. Catching errors should tell you what's going wrong, i would expect an error in your console anyway that would help us out finding the answer even more.
KB.find({}, (err, photos) => {
if (err) res.status(401).send(err)
res.status(200).json(photos)
})
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