How to see cyrillic data in json use node.js restful API - node.js

I have a cyrillic data in json format and in the API I see the data like this:
stations
0
Map_code 0
NAME_IME "Bjala river - Smoljan"
NAME_CYR "���� ���� - ��. ������"
Alertlevelwebsite 1
CODENUM 1
I want to display NAME_CYR "���� ���� - ��. ������" with UTF-8 or CP_1251 encode but I don't know how..?
The code:
app.route('/stations')
.get(function (req, res) {
// omitted
res.setHeader('Access-Control-Allow-Origin', '*', 'Cache-Control', 'private, no-cache, no-store, must-revalidate');
pool.query(`SELECT * FROM sel_alert_level s;`, function (error, result) {
if (error)
return res.status(500).json({ error: "Грешна заявка. Опитай отново !"})
stations = result;
res.json({ stations })
});
});
I try to put res.set({ 'content-type': 'application/json; charset=utf-8' }); before res.setHeader('Access-Control-Allow-Origin', '*', 'Cache-Control', 'private, no-cache, no-store, must-revalidate'); like this:
app.route('/stations')
.get(function (req, res) {
// omitted
res.set({ 'content-type': 'application/json; charset=utf-8' });
res.setHeader('Access-Control-Allow-Origin', '*', 'Cache-Control', 'private, no-cache, no-store, must-revalidate');
pool.query(`SELECT * FROM sel_alert_level s;`, function (error, result) {
if (error)
return res.status(500).json({ error: "Грешна заявка. Опитай отново !"})
stations = result;
res.json({ stations })
});
});
But this not work for me..

You need to check the headers from the response (use dev tools if you're using the browser). JSON is UTF-8 by default and if you use express it should be fine, but just double check.
If that doesn't work - use res.set({ 'content-type': 'application/json; charset=utf-8' }); (Express again).

Related

Empty request body in server, Object object into DB

I'm using NodeJS+express and React. The request body's expected output is "tipologia", but it actually returns an empty object.
I have looked for similar questions (there a lot of them) but none of these is useful.
client:
function CreateStudyPlan(tipologia){
return new Promise((resolve, reject) => {
fetch((URL+'/PianoStudio'), {
method: 'POST',
credentials: 'include',
headers: {
"Access-Control-Allow-Headers" : "Content-Type",
"Access-Control-Allow-Origin": "*"
},
body: JSON.stringify(tipologia),
}).then((response) => {
if (response.ok) {
resolve(null);
} else {
// analyze the cause of error
response.json()
.then((message) => { reject(message); }) // error message in the response body
.catch(() => { reject({ error: "Cannot parse server response." }) }); // something else
}
}).catch(() => { reject({ error: "Cannot communicate with the server." }) }); // connection errors
});
}
server:
// set-up the middlewares
app.use(morgan('dev'));
app.use(express.json());
const corsOptions = {
origin: 'http://localhost:3000',
credentials: true,
};
app.use(cors(corsOptions));
const isLoggedIn = (req, res, next) => {
if(req.isAuthenticated())
return next();
return res.status(401).json({ error: 'not authenticated'});
}
app.post('/PianoStudio', isLoggedIn, async (req, res) => {
try {
await dao.createPianoStudio(req.body, req.user.id);
res.status(201).json(req.body);
} catch(err) {
console.log(err);
res.status(503).json({error: `Database error during the creation of piano di studi for user ${req.user.id}.`});
}
});
The problem is that req.body is empty and should not be ( i am expecting it to output part-time):
The insert into the DB shows that req.user.id is ok, while req.body is an empty Object:
--
2 WORDS ON REQUEST ID AND BODY:
req.body should be the
body: JSON:Stringify(tipologia)
from the client, while req.user.id is retrieved by the session through the isLoggedIn.
2 WORDS ON HEADERS:
At first i had
headers: {
'Content-Type': 'application/json',
But it gave me CORS error:
Access to fetch at 'http://localhost:3001/PianoStudio' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
So i changed the Headers to
headers: {
"Access-Control-Allow-Headers" : "Content-Type",
"Access-Control-Allow-Origin": "*"
}
as
putting 'Content-Type': 'application/json', returns again CORS error.
You should try to define tipologia as an object, in the Client:
body: JSON.stringify({tip_str: tipologia})
While in your Server, you will retrieve your tipologia as follows:
dao.createPianoStudio(req.body.tip_str, req.user.id)

Get request works with postman but with browser

Get request sent from POSTMAN works but when sent from browser fails.
At the backend req.body is undefined even after using bodyparser middleware.
The same requet when sent from the POSTMAN works.
This is the axios call from the frontend.
await axios.get(`${API_URL}/api/authenticate`, {
accesstoken: localStorage.getItem("accesstoken")
},
{
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Access-Control-Allow-Origin': '*',
'Accept-Encoding': 'gzip, deflate, sdch'
}
})
.then((res) => console.log(res))
.catch((err) => {
localStorage.removeItem("accesstoken");
console.log(err)
});
This is the backend auth handler
const isAuthenticated = (req,res,next)=>{
const accesstoken = req.body.accesstoken;
console.log(req.body);
if(!accesstoken)
{
res.json({msg:"No token provided"});
}
else
{
jwt.verify(accesstoken,process.env.ACCESS_TOKEN_SECRETE,(err,decoded)=>{
if(err)
{
res.json({msg:"Invalid token"});
}
else
next();
});
}
}
These are the cors options
app.use(cors({
origin:["http://localhost:3000","http://192.168.0.86:3000"],
optionsSuccessStatus:200,
credentials:true,
allowHeaders:["Content-Type"]
}));
The method signature you are using for axios.get applies to axios.post where the second parameter is the request body. This doesn't hold true for axios.get. You can pass query paramters as second argument of axios.get. Postman is allowing you to make GET requests with body and the server is okay with that but it isn't advised to do so. For your use case of authentication, use POST.
I guess, you meant to do axios.post:
await axios.post(`${API_URL}/api/authenticate`, {
accesstoken: localStorage.getItem("accesstoken")
},
{
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Access-Control-Allow-Origin': '*',
'Accept-Encoding': 'gzip, deflate, sdch'
}
})
.then((res) => console.log(res))
.catch((err) => {
localStorage.removeItem("accesstoken");
console.log(err)
});

Why is res.header() not working in express?

I am trying to authenticate a user for login. However, I don't manage to send a response header.
Login function
// POST /users/login
router.post('/users/login', async (req, res) => {
try {
const body = _.pick(req.body, ['email', 'password']);
const user = await User.findByCredentials(body.email, body.password);
const token = await user.generateAuthToken();
req.session['token'] = 'Bearer ' + token;
req.session['user'] = user;
// the following line does not seem to work properly
res.header('Authorization', 'Bearer ' + token).send(user);
} catch (err) {
res.status(401).json({ message: "Nutzerdaten sind nicht korrekt" });
}
});
Axios plugin
$axios.onResponse(res => {
console.log(res.headers) // does not return an authorization header
if (res.headers.authorization) {
store.commit('auth/SET_TOKEN', res.headers.authorization)
}
return res
})
console.log(res.headers)
'x-powered-by': 'Express',
vary: 'Origin',
'access-control-allow-credentials': 'true',
'content-type': 'application/json; charset=utf-8',
'content-length': '2',
etag: 'W/"2-l9Fw4VUO7kr8CvBlt4zaMCqXZ0w"',
date: 'Tue, 30 Jul 2019 12:35:00 GMT',
connection: 'keep-alive'
I would be very thankful for any kind of help!

nodejs request target url

i want to get the result for this target url. by browser the result is ok, but this nodejs code don't work. i wish someone can help me,thanks a lot.
var request = require('request');
request = request.defaults({
headers: {
Accept: '*/*',
'Content-Type': 'application/json',
}
});
request('http://xueqiu.com/stock/search.json?code=alibaba', function(error, res, body) {
if (error) {
console.log(error);
} else {
console.log(res);
}
});
You can get the cookie from xueqiu.com homepage before hitting this URL. Cookies can be reused using a jar
var request = require('request');
request = request.defaults({
headers: {'Accept': '*/*',
'Content-Type': 'application/json'},
jar: true // reuse cookies across requests
});
request('http://xueqiu.com', function() {
request('http://xueqiu.com/stock/search.json?code=alibaba', function(error, res, body) {
if (error) {
console.log(error);
} else {
console.log(res);
}
});
});

Mashape Imgur node.js image upload

Trying to upload users image but without success.
HTML:
Front-End JS:
var fileInput = document.getElementById('gg_test_input');
fileInput.addEventListener('change', function(e) {
var file = fileInput.files[0];
var xhr = new XMLHttpRequest();
var formData = new FormData();
formData.append("file", file);
xhr.open('POST', '/gg_upload');
xhr.send(formData);
});
Node.js that we sending a request to:
function(req, res){
var form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files) {
if( err ) throw err;
unirest.post('http://httpbin.org/post')
.header("X-Mashape-Key", "MASHAPE_KEY")
.header("Authorization", "clientID_KEY")
.attach('file', files.file.path)
.end(function (response) {
console.log(response.status, response.headers, response.body);
});
});
}
But I get just:
403 { 'access-control-allow-headers': 'Authorization, Content-Type, Accept, X-Mashape-Authorization',
'access-control-allow-methods': 'GET, PUT, POST, DELETE, OPTIONS',
'access-control-allow-origin': '*',
'cache-control': 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0',
'content-type': 'application/json',
date: 'Sat, 15 Nov 2014 10:01:20 GMT',
etag: '"********************************************"',
server: 'Mashape/5.0.5',
'x-ratelimit-requests-limit': '12500',
'x-ratelimit-requests-remaining': '12468',
'x-ratelimit-uploads-limit': '1250',
'x-ratelimit-uploads-remaining': '1248',
'content-length': '110',
connection: 'keep-alive' } { data:
{ error: 'Malformed auth header',
request: '/3/image',
method: 'POST' },
success: false,
status: 403 }
But when tested auth with this curl it is working OK:
curl -X POST --include "https://imgur-apiv3.p.mashape.com/3/image" -H "X-Mashape-Key: MASHAPE_KEY" -H "Authorization: Client-ID clientID_KEY" -F "image=#/home/user/Desktop/face.jpg"
PLEASE, what would be the unirest.post ? Do I need provide more information?
Unfortunately the Node.js example code on Mashape is wrong, you should use this:
var unirest = require('unirest');
unirest.post("https://imgur-apiv3.p.mashape.com/3/image")
.header("X-Mashape-Key", "MASHAPE_KEY")
.header("Authorization", "Client-ID CLIENT_ID")
.header("Content-Type", "multipart/form-data")
.attach("image", "/Users/example/Projects/imgur/test_image.jpeg")
.end(function (result) {
console.log(result.status, result.headers, result.body);
});
You Client ID header is malformed (compare with cURL), if you fix that then it will work

Resources