Message received from background. Values reset - node.js

I'm sending post request from "angular->port 4200" to "expressjs server->port 8000".
As an example i'm folowing this example: https://github.com/kuncevic/angular-httpclient-examples/blob/master/client/src/app/app.component.ts
I'm getting two error :
1)undefined from Nodejs(data and req.body.text)
2)Message received from background. Values reset
Angular side:
callServer() {
const culture = this.getLangCookie().split("-")[0];
const headers = new HttpHeaders()
headers.set('Authorization', 'my-auth-token')
headers.set('Content-Type', 'application/json');
this.http.post<string>(`http://127.0.0.1:8000/appculture`, culture, {
headers: headers
})
.subscribe(data => {
});
}
expressjs side:
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
var path = require('path');
app.all("/*", function(req, res, next){
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
next();
});
app.use( bodyParser.json() ); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
app.post('/appculture', function (req, res) {
var currentCulture = `${req.body.text} from Nodejs`;
req.body.text = `${req.body.text} from Nodejs`;
res.send(req.body)
})
app.listen(8000, () => {
console.log('server started');
})

Either you are not sending anything of there is no value in body.text
Try to console.log(req.body) instead of req.body.text.
Try to console.log(culture) and this.getLangCookie() on the client side to see if you are actually sending something.
You can also make use of the network tab in the browser to inspect the request that you are sending.

Angular side:
callServer() {
const culture = this.getLangCookie().split("-")[0];
const headers = new HttpHeaders()
headers.set('Authorization', 'my-auth-token')
headers.set('Content-Type', 'application/json');
this.http.get(`http://127.0.0.1:8000/appculture?c=` + culture, {
headers: headers
})
.subscribe(data => {
});
}
Nodejs side:
app.get('/appculture', function (req, res) {
currentCulture = req.query.c;
res.send(req.body)
})

Related

CORS on react request to node.js API

This is my node,js API,that works with no problems using postman, but when I try to make a request from a different origin like a react project the request is blocked
const express = require('express');
const mongoose = require('mongoose');
const app = express();
const port = process.env.PORT || 9000;
const routes = require('./routes/routes');
const token = require('./config/config');
const cors = require('cors')
app.use(cors())
app.use(express.json());
app.use('/api', routes);
app.listen(port, () => console.log('server listening on port', port));
const url = "mongodb://localhost/titles_db";
mongoose.connect(url,{})
.then( () => console.log('DB connected'))
.catch( (e) => console.log('Erorr on db connection'));
and this is the function that is called on my request
searchTitles = (req, res) => {
const terms = req.query.terms;
const format = req.query.format;
titleSchema.find({title: {$regex:terms, $options: 'i'}})
.then( data => {
if(format == 'json')
res.json(data);
else{
res.setHeader("Content-Type", "text/plain");
res.send(data);
}
})
.catch( error => res.json( {message: error}))
}
and here is the function that makes the request on the frontend
const getFieldText = e => {
setTerm({term: e.target.value });
const url = `http://localhost:9000/api/titles/?terms=${e.target.value}&format=json`
fetch(url)
.then(response => console.log(response))
.then(data => console.log(data));
}
even including cors library on node
const cors = require('cors')
app.use(cors())
I get this response
Response { type: "cors", url: "http://localhost:9000/api/titles/?terms=aaaaaa&format=json", redirected: false, status: 403, ok: false, statusText: "Forbidden", headers: Headers, body: ReadableStream, bodyUsed: false }
I added an options array but I have the same result
var corsOptions = {
origin: 'http://localhost:3000',
optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
}
app.use(cors(corsOptions))
configure the cross headers like this (in your server node config):
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', "http://localhost:8080");
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, authorization, Access-Control-Allow-Origin');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', 'true');
// Pass to next layer of middleware
next();
});

Angular post request to NodeJS JSON error

So i am sending a POST request to a nodeJS app, my request in Angular looks like this:
export class SearchComponent {
constructor(private http: HttpClient) {}
newWord = '';
keyword = '';
onClick() {
const headers = new HttpHeaders()
.set('Authorization', 'my-auth-token')
.set('Content-Type', 'application/json');
this.http
.post('http://localhost:3000/search', JSON.stringify(this.keyword), {
responseType: 'text',
headers: headers,
})
.subscribe((data) => {
this.newWord = data;
});
}
}
When i try to console.log the request i get an Unexpected token " in JSON at position 0 error even though i tried all the solutions i could find on stackoverflow this is how my NodeJS app is set and the error:
const bodyParser = require("body-parser");
const express = require("express");
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.all("/*", function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS");
res.header(
"Access-Control-Allow-Headers",
"Content-Type, Authorization, Content-Length, X-Requested-With"
);
next();
});
app.listen(3000, () => {
console.log("Server is running on port 3000");
});
app.post("/search", (req, res) => {
res.send(req.body);
});
The error i get is this:
SyntaxError: Unexpected token " in JSON at position 0
at JSON.parse (<anonymous>)....
Note that the this.keyword gets its value from a input field if i dont use JSON.stringify no error is happening but the req variable is "undefined".
Assuming you are asking how to get back the data. I'm not sure if this will work, but you can give it a try:
Under comments, see that you mean this.keyword. Here is the change I would make
going by axis format, this may be incorrect
.post('http://localhost:3000/search', JSON.stringify(this.keyword), {
responseType: 'text',
headers: headers,
})
instead, try:
.post('http://localhost:3000/search', {
keyword: this.keyword, // changed this
responseType: 'text',
headers: headers,
})
also in your server, you can change to this:
const app = express();
app.use(express.json())
app.use(express.text())
app.use(express.urlencoded({ extended: true }))
(body parser included in express now)
new to the mern stack (have never used Angular) so kind of iffy but hopefully that can help

Firebase Functions - cannot read req.body

I'm having a problem with my Firebase Functions https request.
This is my code to trigger it:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
app.use(function(req, res, next) {
res.setHeader('Content-Type', 'application/json');
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Allow-Methods", "GET, POST");
next();
});
app.use((err, req, res, next) => {
if (err instanceof SyntaxError) {
return res.status(400).send();
};
next();
});
app.post('/fetchPosts', (req, res) => {
exports.fetchPosts(req, res);
});
exports.widgets = functions.https.onRequest(app);
const cors = require('cors')({ origin: true })
exports.fetchPosts = (req, res) => {
console.log(req.body)
console.log(res)
let topics = req.body.topics || ['live'];
let start = req.body.start || 0;
let num = req.body.num || 10;
let next = start+num;
// setting up the response.
});
That looks good as far as I can tell..
Now when I do my api call I do:
var headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
headers.append('Content-Type', 'application/json; charset=UTF-8');
const request = new RequestOptions({ headers: headers });
const url = 'https://my-link.cloudfunctions.net/widgets/fetchPosts';
let payload = {
topics: ["live", "pets"]
}
console.log(JSON.stringify(payload))
this.http.post(url, JSON.stringify(payload), request)
.pipe(map((res:Response) => {
console.log(res.json())
}))
.subscribe(
data => console.log(data),
err => console.log(err),
() => console.log('Got feed')
);
and it just returns topics with just ['live'].. because of the failsafe that I set up on the backend.. but why isn't getting my topics that I'm sending?
Also, when I console.log(req.body) on the backend it just shows {}.. an empty object..
Any ideas why the req.body doesn't seem to work? I do it with start and num as well, but they all revert back to the failsafe.
You must use POST method to handle req.body . In your case, you can handle your variable with req.query
To handle req.body . You can use Postman, then select POST method and post data as JSON . You can read more to use Postman well.

Node JS header problems with ionic

So i am using ionic framwork to make my app and using nodeJS as my backend but i am still a noob in this and i can't seem to figure it out still after 4 days so hopefully someone could answer this problem to me and why would be appreciated.
So for my ionic client side i do this to make a http.post request
progress() {
var headers = new HttpHeaders();
headers.append('Accept', 'application/json');
headers.append('Content-Type', 'application/json');
let options = {headers: headers};
let postData = {
username: this.username,
email: this.email,
password1: this.password1,
password2: this.password2
};
this.http.post('localhost:4000/api/users', postData, options,).subscribe(
data => {
console.log(data);
},
error => {
console.log(error);
});
}
and this is what i am doing to get the data from the server but that's not working
// Packages
let express = require('express');
var request = require('request');
var bodyParser = require('body-parser');
var cors = require('cors');
const app = express();
app.use(cors({origin: 'http://localhost:8100'}));
const port = 4000;
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// Whenever you enter localhost:4000/ //
app.get('/', function (req, res) {
res.send(('Server runs'));
});
app.listen(port, () => console.log(`app listening on port ${port}!`));
app.get('/api/users', (req, res) => {
res.send('api/users page');
request.get({
uri: 'http://localhost:8100/create-account'
}, function (err, res, body) {
console.log('error:', err); // Print the error if one occurred and handle it
console.log('statusCode:', res && res.statusCode); // Print the response status code if a response was received
res.send(body);
});
});
i also tried 'http://localhost:8100' & 'localhost:8100'
so someone help me
You need to add a handler for your POST request. To do this use app.post, and it looks like this
app.post('/api/users', (req, res) => {
// You can find your data here
const data = req.body;
console.log(data);
// Send back a response
res.sendStatus(200);
});

CORS issues even after using npm cors plugin in node server

I have created a simple server in node js to take the request from a react app.
But for the GET method there is no CORS error but whenever I do post, it gives me an error.
For the POST method to work, I have implemented in index.js file of the actions folder and it should hit the url from the server.js file.
index.js
import axios from 'axios';
export const GET_NAVBAR = "GET_NAVBAR";
export const LOGIN = "LOGIN";
export const BASE_API_URL = "http://localhost:3030";
export const GUEST_API_URL = "https://XXX.XXX.XXX.X:5443/wcs/resources/store/1";
export const getNavbar = () => {
return axios.get(BASE_API_URL + '/topCategory').then(res => {
return {
type: GET_NAVBAR,
payload: res.data.express.catalogGroupView
};
});
};
export const login = () => {
return axios.post(GUEST_API_URL + '/guestidentity', {}).then(res => {
console.log(res);
return {
type: LOGIN,
payload: {}
}
}).catch(e => {
console.log(e);
return {
type: LOGIN,
payload: {}
}
});
};
server.js
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const Client = require('node-rest-client').Client;//import it here
const app = express();
const helmet = require('helmet');
const morgan = require('morgan');
// enhance your app security with Helmet
app.use(helmet());
// use bodyParser to parse application/json content-type
app.use(bodyParser.json());
app.use(cors());
// log HTTP requests
app.use(morgan('combined'));
app.post('/guestidentity', (req, res) => {
var client = new Client();
// direct way
client.post("https://XXX.XXX.XXX.X:5443/wcs/resources/store/1/guestidentity", (data, response) => {
res.send({express: data});
});
});
const port = 3030;
app.listen(port, () => console.log(`Server running on port ${port}`));
I don't know where my code is getting wrong. Can anybody please help me to troubleshoot this issue. I would be grateful if someone could provide an insight or guide me a little. Thanks
For my part I used
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
It will accept from any * sources, you might want to change that later
In your server.js , add the following middleware.
var allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', 'http://localhost:3030/');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
};
app.use(allowCrossDomain);

Resources