I have a fetch on React client program which is as below:
checkStatus(response) {
if (response.status >= 200 && response.status < 300) {
return response
} else {
var error = new Error(response.statusText)
error.response = response
throw error
}
};
componentDidMount() {
console.log('in the did mount ' +this.state);
return fetch('/addUser', {
method: 'put',
body: JSON.stringify(this.state),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
})
.then(this.checkStatus)
.then(()=>console.log('updated!!!'))
};
This is App.jsx.
In the Node End of the project I have addUser.js under routers folder, which has the code below:
let router = require('express').Router(); let bodyParser =
require('body-parser');
// parse application/json router.use(bodyParser.json());
router.put('/addUser', update);
function update(req, res) { console.log('updating-', req.body);
res.sendStatus(200); }
The client page is returning:
resource not found: http://localhost:3000/addUser
Is there any config that I am missing in the above.
I have this on a react node project.
Related
I am fetching IGDB api on server because I need to go through CORS. I am using async await connected to client side. Everything works fine but I need to pass query like '/?fields=cover.*,name;limit=50;' to https://api.igdb.com/v4/games from client side, not from server. When I am adding a query to client side, it's still showing the query only from server. How I can pass this query from client side? This is my code:
api/example.js
import Cors from "cors";
import initMiddleware from "../../components/init-middleware";
const cors = initMiddleware(
Cors({
methods: ['GET', 'POST', 'OPTIONS'],
})
)
const settings = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Client-ID': 'my_client-id',
'Authorization': 'Bearer my_authorization',
},
}
const remoteServerUrl = 'https://api.igdb.com/v4/games'
export default async function handler(req, res) {
await cors(req, res)
const response = await fetch(remoteServerUrl, settings);
const data = await response.json()
res.json(data)
}
client side
const settings = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Client-ID': 'my_client-id',
'Authorization': 'Bearer my_authorization',
},
const fetchData = async () => {
let query = '/api/example/'
const response = await fetch(query + HERE I WANT TO ADD QUERY, settings);
const data = await response.json();
}
Edit:
Status Code: 308 Permanent Redirect
initMiddleware
// Helper method to wait for a middleware to execute before continuing
// And to throw an error when an error happens in a middleware
export default function initMiddleware(middleware) {
return (req, res) =>
new Promise((resolve, reject) => {
middleware(req, res, (result) => {
if (result instanceof Error) {
return reject(result)
}
return resolve(result)
})
})
}
I am facing some issue while downloading file using node.js. I have scenario like my angular component is sending the file request. in my first node server I am doing the token validation and then redirecting to another node server where actually the execution happens. I am explaining my code below.
service.ts:
submitAndDownloadFile(formdata : any ){
const token = localStorage.getItem('token')
let headers = new HttpHeaders({
Authorization: 'Basic ' + token
})
const cecID = localStorage.getItem('cec');
const AppUrl = `${environment.nodeJsBaseUrl}:${environment.hostingNodeJsContainerPort}/convert-test-cases/${cecID}`;
return this.httpClient.post(AppUrl, formdata, { responseType: 'blob', observe : 'response', headers : headers});
}
Here I am sending the request to my first node.js server which code has given below.
app.js(first:port-8000):
router.post('/convert-test-cases/:id', middleware.auth, (req, res) => {
try{
let postRequestOptions = {
url: '',
method: 'POST',
json: true,
headers: {},
body: {},
};
postRequestOptions.url = 'http:localhost:9000/convert-test-cases';
postRequestOptions.headers = {
'Content-Type': 'application/json',
};
postRequestOptions.body = req.body;
request(postRequestOptions, async (error, response, pathList) => {
if(error) {
console.log('error', error);
}else{
res.send(pathList);
}
})
}catch(e){
responseObj = {
status: 'error',
msg: 'Error occurred while processing your request',
body: null
}
return res.send(responseObj);
}
})
Here I am doing the token validation using middleware.auth and sending same request to another node.js file which code is explained below.
app.js:(second-port-9000):
router.post('/convert-test-cases', async (req, res) => {
try{
let response = await ctcCtrl.convertTestCase(req.body, req.files);
if(response.status == 'success'){
res.set('Access-Control-Expose-Headers','*, Content-Disposition');
return res.download(response.fileName,response.fileName);
}else{
return res.send(response);
}
}catch(e){
responseObj = {
status: 'error',
msg: 'Error occurred while processing your request',
body: null
}
return res.send(responseObj);
}
})
Here only I am doing some execution and downloading the file. If I am connecting angular to node-9000 its working fine but my requirement is first I have to connect to port-8000 to some token validation and after that I have to send same req.body and re.file to app.js which is running in 9000 using request module. As per my code its not working at all.
I have already searched a lot, but none of the solutions found work: Cannot send content-type by axios. but if I use the postman interceptor and I 'send' the request generated by axios this time it works: the node.js / express server correctly receives the request and body-parser works normally!
React side:
const API_URL = "http://localhost:8800/auth/";
const headers = {
accept: 'application/json, text/plain, */*',
'content-type': 'application/json;charset=UTF-8'
};
class AuthService {
register(pseudo, email, password) {
return axios.post(API_URL + "signup/",
{ pseudo, email, password },
{ headers: headers})
.then(response => {
if (response.data.accessToken) {
localStorage.setItem("user", JSON.stringify(response.data));
}
return response.data;
});
}
server side
const app = express();
app.use(function (req, res, next) {
console.log( req.headers);
next();
});
app.use( bodyParser.urlencoded({ extended: true }), bodyParser.json());
Usually when I use axios I send the headers in a config variable like this and I stringify the body so it sends as JSON object and not a JS object.
const config = {
headers: {
'Content-Type': 'application/json',
},
};
const body = JSON.stringify({arguments});
try {
const res = await axios.post(/url, body, config);
...
Here's a link to the docs for a little more reading about it:
https://github.com/axios/axios
my server can't find the api's that i created in api directory. it leads to 500 internal server.
I have checked routes.js but i see that everything is right. i have an error.js file for file handling. Here's my code.
'use strict';
let router = require('express').Router();
// Middleware
let middleware = require('./controllers/middleware');
router.use(middleware.doSomethingInteresting);
// Tasks
let tasks = require('./controllers/tasks');
let createkeypairs = require('./controllers/createkeypairs');
let importaddress = require('./controllers/importaddress');
let getwalletinfo = require('./controllers/getwalletinfo');
router.get('/tasks', tasks.findAll2);
router.get('/createkeypairs', createkeypairs.findAll);
router.get('/importaddress', importaddress.findAll);
router.get('/getwalletinfo', getwalletinfo.findAll);
router.post('/buggyroute', tasks.buggyRoute);
// Error Handling
let errors = require('./controllers/errors');
router.use(errors.errorHandler);
// Request was not picked up by a route, send 404
router.use(errors.nullRoute);
// Export the router
module.exports = router;
now showing you my createkeypairs.js
'use strict';
let errors = require('./errors.js');
var request = require("request");
var options = { method: 'POST',
url: '127.0.0.1:18332',
headers:
{ 'Authorization': 'Basic bXVsdGljaGFpbnJwYzpHTmJ5enJhMnlHRjN4Ymp1cnluRTFucTlnV1ExRXV3OTFpYVBqSkt5TkJxdA==',
'cache-control': 'no-cache',
'Cache-Control': 'no-cache',
'Content-Type': 'application/json' },
body: { method: 'createkeypairs', params: [], chain_name: 'tokenchain' },
json: true };
exports.findAll = (req, res, next) => {
// Simulate task list, normally this would be retrieved from a database
let createkeypairs ;
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log("working here ");
// res.json(body);
});
};
exports.buggyRoute = (req, res, next) => {
// Simulate a custom error
next(errors.newHttpError(400, 'bad request'));
};
I think the problem is in createkeypair file.
Try this code once for your createkeypairs.js:
'use strict';
let errors = require('./errors.js');
var request = require("request");
let config = require('config');
var auth = 'Basic ' + Buffer.from(config.user + ':' + config.pass).toString('base64');
var url = config.url;
var chain = config.chain;
var options = { method: 'POST',
url: url,
headers:
{ 'cache-control': 'no-cache',
Authorization : auth,
'Content-Type': 'application/json' },
body: { method: 'importaddress', params: ["address"], chain_name: chain },
json: true };
exports.findAll = (req, res, next) => {
// Simulate task list, normally this would be retrieved from a database
let createkeypairs ;
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
res.json(body);
});
};
exports.buggyRoute = (req, res, next) => {
// Simulate a custom error
next(errors.newHttpError(400, 'bad request'));
};
Do tell me if it works or not.
I am using nodejs as back-end for angular 5 application . When I am posting data with http post request then it coming at nodejs in wrong formate (Values as property)-
This is my service code of angular 5 -
login(email: string, password: string) {
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
let options = new RequestOptions({ headers: headers });
let body = { EmailAddress: email, Password: password };
return this.http.post('http://localhost:3000/api/user/login', body, options )
.map((response: Response) => {
let user = response.json();
if (user && user.token) {
localStorage.setItem('currentUser', JSON.stringify(user));
}
});
}
This is Node API - in body I am getting value as property
app.post('/api/user/login', urlencodedBodyparser, function (req, res) {
console.log(req.body);
User.find({ "EmailAddress": req.body["EmailAddress"], "Password": req.body["Password"] }, function (err, users) {
console.log(users.length);
if (err != null) {
sendError(err, res);
}
if (users != null) {
var count = users.length;
if (count > 0) {
response.data = users[0];
res.json(response);
}
else {
sendError({ message :'No user found'}, res);
console.log("Login Failed");
}
}
else {
sendError(err, res);
}
})
});
Code for body parser -
var bodyParser = require('body-parser');
var urlencodedBodyparser = bodyParser.urlencoded({ extended: false });
app.use(urlencodedBodyparser);
try to change the header content-type to json
application/json
like this:
options() {
const headers = new Headers({
'content-type': 'application/json'
});
const options = new RequestOptions({ headers: headers });
return options;
}
login(): Observable<any> {
return this.http.post('http://localhost:3000/api/user/login', this.options()).
map((res: Response) => res.json());
}
You need to use body-parser middleware https://github.com/expressjs/body-parser
Here is more information What does body-parser do with express?
Try to use this :
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));