I'm trying to send data using vue.js to my node.js server, but the browser console keeps showing me a 404: POST http://127.0.0.1:63342/myaction 404 (Not Found)
vue.js:
this.$http.post('http://127.0.0.1:63342/myaction', this.formData).then(response => {
console.log(response.body);
}
node.js:
var express = require('express');
var bodyParser = require('body-parser');
var exp = express();
exp.use(bodyParser.urlencoded({extended: true}));
exp.post('/myaction', function (req, res) {
res.send('saved: "' + req.body.name + '".');
});
exp.listen(63342, function () {
console.log('Server running at', this.address());
});
When I start my server, it says it's running at { address: '::', family: 'IPv6', port: 63342 }
The POST worked without vue.js, by simply submitting a HTML form, but now AJAX doesn't wordk. I tried multiple ports and folders, but can't figure out the mistake.
I finally figured it out. You have to manually add an address to the listener:
app.listen(63342, '127.0.0.1', function () {}
And in my case I was using the same port for API and Frontend, I had to switch ports and allow CORS
Related
I'm using both Ubuntu and Visual Studio Code to launch my server program, they were both sucessfully taking and sending back replies from Postman a few days ago. The server code runs fine, and says the server is up and running at https://loccalhost:8080
But when I try to send a GET request from Postman, I get this error from Postman:
This is the environment I'm using:
And this is the error I get from my server program when it gets a request:
How ther server is configured:
require('dotenv').config()
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
app.set("port", 8080);
app.use(bodyParser.json({ type: "application/json" }));
app.use(bodyParser.urlencoded({ extended: true }));
const Pool = require("pg").Pool;
const config = {
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASS,
database: "taskfour"
};
const pool = new Pool(config);
//HELLO WORLD
app.get("/hello", (req, res) => {
res.json({msg: "Hello, World!"});
});
app.listen(app.get("port"), () => {
console.log(`Find the server at http://localhost:${app.get("port")}`);
});
The server had previously been working fine, Postman was sending requests, doing tests, and my code was passing them. I didn't change much in the meanwhile, I'm not sure what changed. I've tried turning off my proxy server on Postman, but it hasnt' helped. Any help would be greatly appreciated.
Looks like the HTTP listening code is missing, for example:
app.listen(8080, function () {
console.log('App listening on port 8080.');
});
Wow, I didn't realize the postgres service wasn't running. I just needed to enter the command "sudo service postgresql start" in my terminal, and the requests work again.
So, I need to hit an API and render the response in a html element. I have my app.js doing this:
let url = 'http://localhost:80/db/abc/query/';
class abc extends Component {
state {userinput:""}
getResponse = () => {
axios.get(url+this.state.userinput, {
headers: {
'Content-Type': 'application/json'
}
})
.then(response => {
this.setState({results: response.data})
});
}
render () { //ignore the render for now
return ()
}
}
export default abc;
But since I was getting the CORS error, I created a server.js & started the proxy using # node server.js command. But for some reason I keep getting Error 500 back from the API.
Server.js
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
app.use('/', function(req, res) {
var url = 'https://' +
req.get('url').replace('localhost:80', 'my-real-host-fqdn:8122') +
req.url
req.pipe(request({ qs:req.query, uri: url })).pipe(res);
})
app.listen(80, function () {
console.log('CORS-enabled web server listening on port 80')
})
I call my getResponse() on a button click, which is working but not included in the excerpt above.
Error Messages:
GET http://localhost/db/abc/query/<userinput> 500 (Internal Server Error)
createError.js:17 Uncaught (in promise) Error: Request failed with status code 500
Errors with proxy server:
CORS-enabled web server listening on port 80
TypeError: Cannot read property 'replace' of undefined
OR
CORS-enabled web server listening on port 80
ReferenceError: request is not defined
I am not very familiar with the server.js file and using express. How does this work, and have I made any mistakes here?
So what did the trick for me was removing this line from my server.js:
req.pipe(request({ qs:req.query, uri: url })).pipe(res);
Posting this here so it helps someone with a similar issue.
Thanks for trying to help guys!!
to get host, use req.get('host'). Seems like req.get('url') is the issue.
app.get('/one/two', function (req, res) {
var url = req.url;
}
How to get the full url in Express?
I'm trying to create a basic login script for an app using Express JS, and have been working on a POST function to perform the same task for me. However, whenever I try to echo back the parameters I'm passing (testing the script via Postman), the values are always undefined.
Would appreciate some help! Thanks :)
Code:
const express = require('express'),
app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/',(request,response)=>{
response.send('This is a test message');
});
app.post('/login', (request,response)=>{
let uname = request.body.username;
let pword = request.body.password;
response.send('Username: ' + uname + ' and Password: ' + pword);
});
//Binding the server to a port(3001)
app.listen(3001, () => console.log('express server started at port 3001'));
JSON being passed:
{
"username":"testuname",
"password":"passw0rd"
}
What you have works fine.
You are probably not specifying the Content-Type of your request to be application/json when testing.
I think you should try as like as give below:
It works on my machine. As you might have seen that, I have select raw and JSON(application/json) which you might have been missing.
So I'm querying the Blizzard API Battle.Net for some information, character name and the realm they're in. Ofcourse it's possible for a user to query for a character that Does Not Exist, so Blizzard throws a 404 back to me and my server.js file doesn't know what to do with it even though I put something in place to handle it.
Releveant server.js code:
var express = require('express');
var app = express();
var fs = require('fs');
var bodyParser = require('body-parser');
var jsonParser = bodyParser.json();
const blizzard = require('blizzard.js').initialize({apikey: "dummy"});
app.use(express.static(__dirname + '/Source'));
//Listen on port 3000
app.listen(3000, function() {
console.log("Launch successful. To access app, open your browser and insert the following URL into your address bar: http://localhost:3000/");
});
app.post('/buttonpress', jsonParser, function (req, res) {
blizzard.wow.character(['profile'], { origin: 'us', realm: req.body.realm.name, name: req.body.name })
.then(response => {
if(response.status != 200){
res.send("That character doesn't exist! Please enter a valid character name.");
} else {
console.log(response.data);
res.send(response.data);
}
});
});
I attempt to handle anything that's not a 200 by sending something to the client to tell the user: Character DNE!, but instead vscode gives me some red error codes mentioned in the title of this post (in vscode debugger anyway).
When I try this from a command line, just running node server.js, nothing happens when I click the Search Button. I've set breakpoints and it looks like the function doesn't get a response from the server. So the 404 is happening no matter what but I can't figure out how to handle it.
Try placing your app.listen below/after your app.post Express.js runs in a middleware functionality so your listen is blocking all preceding code.
I am making a simple POST request using Alamofire (in iOS) and handling it in node using express.
My code in iOS:
let boop: [String: AnyObject] = ["username":"fakeuser"];
Alamofire.request(.POST,"http://localhost:3000/test", parameters: boop, encoding: .JSON)
And this is my code in node:
var app = require('express')();
var http = require('http').Server(app);
app.post('/test', function(req, res){
console.log("THE SERVER HAS RECEIVED THE POST! \n")
console.log(req.body);
});
http.listen(PORT, function(){
console.log('listening on *:3000');
});
My terminal console prints out "the server has received the post" , so I know that the post is actually triggered. The issue is that instead of logging the req.body, it instead prints out "undefined". I've looked around and it seems like a "body parser" thing needs to be configured but apparently that is obsolete with the new version of express. So I am lost as to what to do.
Any advice?
I'm pretty sure you need to add the body-parser to your express app to parse the JSON.
const bodyParser = require('body-parser');
app.use(bodyParser.json());
See http://expressjs.com/de/api.html#req.body.