I have tried build an api using node.js (+express).
The Firefox display it but when I try to load it with loadJSON from p5.js it shows weird error.
Here is node.js code (based on this: modulus: create api with node.js ):
express = require("express");
app = express();
app.listen(4000);
var quotes = [
{ author : 'Audrey Hepburn', text : "Nothing is impossible, the word itself says 'I'm possible'!"},
{ author : 'Walt Disney', text : "You may not realize it when it happens, but a kick in the teeth may be the best thing in the world for you"},
{ author : 'Unknown', text : "Even the greatest was once a beginner. Don't be afraid to take that first step."},
{ author : 'Neale Donald Walsch', text : "You are afraid to die, and you're afraid to live. What a way to exist."}
];
app.get('/', function(req, res){
res.json(quotes);
})
p5.js:
function setup() {
loadJSON("http://localhost:4000/", getJson, error1);
}
function getJson(data) {
console.log("json get");
console.log(data)
}
function error1(err) {
console.log("Error: ");
console.log(err);
}
Error:
"Error: "
{
"statusText": "",
"status": 0,
"responseURL": "",
"response": "",
"responseType": "",
"responseXML": null,
"responseText": "",
"upload": {
"ontimeout": null,
"onprogress": null,
"onloadstart": null,
"onloadend": null,
"onload": null,
"onerror": null,
"onabort": null
},
"withCredentials": false,
"readyState": 4,
"timeout": 0,
"ontimeout": null,
"onprogress": null,
"onloadstart": null,
"onloadend": null,
"onload": null,
"onerror": null,
"onabort": null
}
I have tried using 'jsonp' but it shows this:
5209: Uncaught TypeError: Cannot read property 'responseText' of undefined
I have node.js v4.2.2 and p5.js v0.5.4 October 01, 2016.
I seems likely that you have a cross origin issue when accessing the API from a browser.
What errors do you see in the browser console? If so, you can fix it by either allowing cross origin access on your server or by loading your web page from the same web server (which would make your api the same origin).
Related
This is the first time i post a question here, sorry if some data is missing.
I'm trying to do some web scraping to get some info of a table.
The page only responds with an index.php and when i use the search form, it makes a POST to index.php?go=le with some formData.
To avoid the CORS problem, im making the post with my own API running in localhost. I'm pointing my frontend to my API and i get the response from localhost.
No problem there.
My problem appears when i try to make a second request to my API. The first GET works fine but after that response it keeps failing.
When i restart the server, it works again but only one time.
Here is my API code. I use nodemon server.js to start my server.
server.js
const express = require("express");
const axios = require("axios");
const scrape = require("scrape-it");
const FormData = require("form-data")
const cors = require("cors")
const app = express();
const PORT = process.env.PORT || 5000;
app.use(cors())
const config = {
headers: {
'Content-type': 'multipart/form-data'
},
}
app.get("/get-projects", async (req,res) => {
const testJSON = await axios.post(baseURL +"/index.php?go=le",formData,config)
.then(res => {
console.log("Post successfull...");
return res
}
)
.catch(err => {
console.log("Server error");
return err
}
);
if(testJSON && testJSON.data){
res.send({status: 200, data: testJSON.data});
}else{
res.status(508).send({status: 508, msg: "Unhandled Server Error", failedResponse: testJSON || "empty"})
}
})
app.listen(PORT,()=>console.log(`App running in port: ${PORT}`))
And in my front-end i only have a button with an event that makes a get to my API (http://localhost:5000)
This is my fetch.js that is included by a script tag. Nothing fancy there.
fetch.js
const btn = document.getElementById("btn-fetch-proyects")
const axios = window.axios
const fetchProjects = async () => {
console.log("Fetching...")
axios.get("http://localhost:5000/get-projects")
.then(res=>
console.log("The server responded with the following data: ",res.data)
)
.catch(err => console.log("Failed with error: ",err)
)
return null
}
btn.addEventListener("click",fetchProjects);
In the console where im running the server, i get Server error with this err object:
{
"message": "socket hang up",
"name": "Error",
"stack": "Error: socket hang up\n at connResetException (internal/errors.js:607:14)\n at Socket.socketOnEnd (_http_client.js:493:23)\n at Socket.emit (events.js:327:22)\n at endReadableNT (internal/streams/readable.js:1327:12)\n at processTicksAndRejections (internal/process/task_queues.js:80:21)",
"config": {
"url": "http://186.153.176.242:8095/index.php?go=le",
"method": "post",
"data": {
"_overheadLength": 1216,
"_valueLength": 3,
"_valuesToMeasure": [],
"writable": false,
"readable": true,
"dataSize": 0,
"maxDataSize": 2097152,
"pauseStreams": true,
"_released": true,
"_streams": [],
"_currentStream": null,
"_insideLoop": false,
"_pendingNext": false,
"_boundary": "--------------------------935763531826714388665103",
"_events": {
"error": [
null,
null
]
},
"_eventsCount": 1
},
"headers": {
"Accept": "application/json, text/plain, */*",
"Content-Type": "multipart/form-data",
"User-Agent": "axios/0.21.1"
},
"transformRequest": [
null
],
"transformResponse": [
null
],
"timeout": 0,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1,
"maxBodyLength": -1
},
"code": "ECONNRESET"
}
I hope someone has a clue about what's happening. I tried all day and i couldn't solve it.
I tried posting to other sites, and it works fine. I thing the problem is with the form POST.
Thanks for reading!!!
At a first glance I see an error in your front-end code. You are using async on the function but then you do not await but you use .then, try not mixing up styles, either you use async/await or .then .catch.
Check if that helps! :)
Obviously the socket is hanging!
Use node unirest and it closes the data stream.
var unirest = require('unirest');
var req = unirest('POST', 'localhost:3200/store/artifact/metamodel')
.attach('file', '/home/arsene/DB.ecore')
.field('description', 'We are trying to save the metamodel')
.field('project', '6256d72a81c4b80ccfc1768b')
.end(function (res) {
if (res.error) throw new Error(res.error);
console.log(res.raw_body);
});
Hope this helps!
im trying to use this pakcage
https://www.npmjs.com/package/signalr-client
to talk with SignalR api written in c# , but i get some error just when i trying to create the client
here is my code
var signalR = require('signalr-client');
try
{
var client = new signalR.client(
"https://firouzex.exphoenixtrade.com/realtime",
['GetNewAPIToken' , 'OmsClientHub']
);
}
catch (e) {
console.log('error');
}
but i get this error
Error Message: Protocol Error
Exception: undefined
Error Data: Url {
protocol: 'https:',
slashes: true,
auth: null,
host: 'firouzex.exphoenixtrade.com',
port: null,
hostname: 'firouzex.exphoenixtrade.com',
hash: null,
search:
'?connectionData=%5B%7B%22name%22%3A%22getnewapitoken%22%7D%2C%7B%22name%22%3A%22omsclienthub%22%7D%5D&clientProtocol=1.5',
query:
[Object: null prototype] {
connectionData: '[{"name":"getnewapitoken"},{"name":"omsclienthub"}]',
clientProtocol: '1.5' },
pathname: '/realtime/negotiate',
path:
'/realtime/negotiate?connectionData=%5B%7B%22name%22%3A%22getnewapitoken%22%7D%2C%7B%22name%22%3A%22omsclienthub%22%7D%5D&clientProtocol=1.5',
href:
'https://firouzex.exphoenixtrade.com/realtime/negotiate?connectionData=%5B%7B%22name%22%3A%22getnewapitoken%22%7D%2C%7B%22name%22%3A%22omsclienthub%22%7D%5D&clientProtocol=1.5',
headers: {} }
Known issue "client.Proxy settings currently only work for HTTP and not HTTPS". There is an another package for https https://www.npmjs.com/package/signalrjs. Copied it from npm package for signalr client not getting connected
I'm building an app using MEAN stack. I'm using Proxy config file to make requests to the backend which is written in Node JS.
proxyconfig.json
{
"/api/*": {
"target": "https://localhost.com:3333",
"secure": false,
"changeOrigin": true,
"pathRewrite": {
"^/api": "https://localhost.com:3333/api"
}
}
}
Code in Component file
this.http.get("/api/posts",{responseType: 'text'})
.subscribe(
data =>
{
console.log('successs');
},
error =>
{
console.log(error);
}
);
Code in Node JS server
app.get('/api/posts', function(req, res) {
console.log('Posts Api Called');
res.status(200).send({ data: 'somedata' });
});
I'm getting 500 error when I inspect the request from Chrome. The GET method is not getting called at all. What could be the cause?
Finally, I made a silly mistake and this worked for me.
{
"/api": {
"target": "https://localhost:3333/api",
"secure": false,
"changeOrigin": true,
"pathRewrite": {"^/api" : ""}
}
}
I have an Django project using Celery with RabbitMQ broker. And now I want to call django (celery) task from NodeJS server.
In my NodeJS I'm using amqplib. Which is allow me to send tasks to RabbitMQ:
amqp.connect('amqp://localhost', function(err, conn) {
conn.createChannel(function(err, ch) {
var q = 'celery';
ch.assertQueue(q, {durable: true});
ch.sendToQueue(q, new Buffer('What should I write here?'));
});
});
My question is what format celery use? What should I write to Buffer to call celery worker?
For example, in my CELERY_ROUTES (django settings) I have blabla.tasks.add:
CELERY_ROUTES = {
...
'blabla.tasks.add': 'high-priority',
}
how to call this blabla.tasks.add function?
I've tried many ways but celery worker giving me error: Received and deleted unknown message. Wrong destination?!?
I found solution http://docs.celeryproject.org/en/latest/internals/protocol.html here.
Example message format is:
{
"id": "4cc7438e-afd4-4f8f-a2f3-f46567e7ca77",
"task": "celery.task.PingTask",
"args": [],
"kwargs": {},
"retries": 0,
"eta": "2009-11-17T12:30:56.527191"
}
So code should be:
amqp.connect('amqp://localhost', function(err, conn) {
conn.createChannel(function(err, ch) {
var q = 'celery';
ch.assertQueue(q, {durable: true});
ch.sendToQueue(q, new Buffer('{"id": "this-is-soo-unique-id", "task": "blabla.tasks.add", "args": [1, 2], "kwargs": {}, "retries": 0}'), {
contentType: 'application/json',
contentEncoding: 'utf-8',
});
});
});
I have this err:authentication:invalid_token in json file. folder is setup as locales/vi_VN/mynamespace-vi_VN.json. However, it's not translating in the console.log below.
Any idea why?
i18n.init({
debug: true,
preload: ['vi_VN'],
resGetPath: 'locales/__lng__/__ns__-__lng__.json',
lng: 'en_GB',
ns: 'mynamespace',
sendMissingTo: 'fallback',
fallbackLng: 'en_GB'
}, function(err, t) {
console.log('i18n is initialized.')
console.log('Translation on:', t('err:authentication:invalid_token', {
lng: 'vi_VN'
}))
})
My bad, i was using colon : in identifier. I need to change it to something else or put it in appropriate namespace