I'm learning about servers and APIs, I do not know too much about how data is received and sended through requests. So i got my server with Node.js using Mongoose and Express.js:
server.get('/api/items', async (req, res)=>{
let results = await TvModel.find({model: 4013});
res.json(results);
});
So if i send the get request via postman i get this:
[
{
"_id": "60f62a33a1dbf8031088cd3b",
"name": "Sony",
"model": "4013",
"size": 8,
"idSerial": 1,
"__v": 0
}
]
So, trying to get the data via JavaScript using fetch api:
fetch(API_URL, {mode: 'no-cors'})
.then((resolve) => {resolve.json()})
When executing this code, i get an error on the console:
Uncaught (in promise) SyntaxError: Unexpected end of input
What is the SyntaxError i cannot see?
I solved it myself by doing the following:
Thanks to #Bravo's answer, I was able to get an idea of what my error was:
"did you add that header due to a CORS error perhaps thinking this
will bypass CORS?"
Since I am using express.js for my server, I had to install a middleware for my server, an npm module called "cors".
So the only thing i needed to add was this line of code:
const cors = require('cors');
app = express();
app.use(cors());
Anyway you can read more of this on official documentation of cors in the official express.js website
Related
I'm currently trying to make a node.js script to read a couple of RSS feeds from a JSON file (config.json), check everyone and send new items to it's specific webhook for Discord.
The config file is the following:
[
{
"name": "r/aww",
"avatar": "https://example.com/avatar.jpg",
"rss_url": "https://www.reddit.com/r/aww/top/.rss",
"webhook_url": "https://discord.com/api/webhooks/..."
},
{
"name": "r/ImaginaryLandscapes",
"avatar": "https://example.com/avatar.jpg",
"rss_url": "https://www.reddit.com/r/ImaginaryLandscapes/top/.rss",
"webhook_url": "https://discord.com/api/webhooks/..."
}
]
And the code that i attempted to do, following sync examples from rss-parser npm package, is the following:
let Parser = require('rss-parser');
let parser = new Parser();
const config = require("./config.json");
config.forEach(element => {
parser.parseURL(element.rss_url, function(err, feed) {
console.log(feed);
feed.items.forEach(function(entry) {
console.log(entry.title + ':' + entry.link);
});
});
});
But trying to run it throws the following error:
undefined
/mnt/d/misc/feedchecker/script.js:28
feed.items.forEach(function(entry) {
^
TypeError: Cannot read property 'items' of undefined
at /mnt/d/misc/feedchecker/script.js:28:9
at Timeout.setTimeout [as _onTimeout] (/mnt/d/misc/feedchecker/node_modules/rss-parser/lib/utils.js:63:29)
at ontimeout (timers.js:436:11)
at tryOnTimeout (timers.js:300:5)
at listOnTimeout (timers.js:263:5)
at Timer.processTimers (timers.js:223:10)
What I'm doing wrong on this code? Please note that i still didn't wrote the webhook sending part, I'm focused still on fetching the feeds first.
I suspect this specific error was caused because i was (without knowing) using Node.JS v10 (that is the version that is shipped by apt by default for WSL's Ubuntu).
Reinstalling Node.JS using NodeSource repository gives me the version 16 that is able to run the code without issues.
I'm a new one, I'm trying to fetch my own api on local,this what I do:
in "src/server.js"
const express = require("express");
const app = express();
app.get("/api", (request, response) => {
response.sendFile("api.js", { root: __dirname });
});
app.listen(8000);
then I use creat-react-app to create a react project, how can I call my api in App.js?
if my situation is not complete, please tell me.
Q1:with server.js, after I run "node server.js", I can can call this file in browser that means I have done an api, right?
Q2:how can I get value from my api.js in App.js without cors problem?
Firstly you should add your request address into package.json file. For example if you want to send http request to https://localhost:5000/, you should add "proxy":"http://localhost:5000" line into your package.json file.
After adding this line, you can send http request without getting CORS error.
Also you can use fetch function to sending request and getting response from server side in your react code(App.js).
fetch('/api')
.then((response) => response.json())
.then((data) => console.log(data));
I am currently working on a react/express project and I get this error:
Error: A cross-origin error was thrown. React doesn't have access to the actual error object in development. See https://reactjs.org/link/crossorigin-error for more information.
I have enabled CORS in my server.js like this:
const express = require("express"),
app = express(),
port = process.env.PORT || 5000,
cors = require("cors");
{Sequelize, Model, QueryTypes } = require('sequelize');
app.use(cors());
app.use(express.json());
I also have no issues with displaying the original data in console.
This is basically what causes it to break.
allDetails=JSON.parse(details);
Getting and sending the data:
async function connect() {
var detailsArray=[]
try {
await sequelize.authenticate();
console.log('Connection has been established successfully.');
} catch (err) {
console.error('Unable to connect to the database:', error);
}
info = await sequelize.query('select * from Information', { type: QueryTypes.SELECT });
let details = JSON.stringify(info);
detailsArray=JSON.parse(details);
return details;
}
app.get("/list", async (req, res) => {
const result = await connect();
res.json(result);
});
I also made sure to npm install for both my client and server side a few times to double check and triple check that it was installed.
Am I missing something?Or do I need anything in my client side to solve this issue. This is very confusing and whatever solution I tried for my CORS issue did not work either. Powershell is also not giving any errors regarding me trying to parse my data. I am not very familiar with cross origin related errors so an explanation would be very much appreciated.
When this error happens:
The error happens when I try to JSON.parse() the data received but when using console.log to display the raw data it is fine. So before that nothing breaks.
If I understand correctly, you are running both front-end and server on your local machine during development and getting CORS error, if so, since you are using express and have already required the CORS module, you still need to use it as a middleware to your express app - Express - Using middleware:
const express = require("express");
const app = express(),
const port = process.env.PORT || 5000,
const cors = require("cors");
app.use(cors());
app.listen(5000);
So, i've been working on backend for my app. The error is in the request, when posting user data.
const db = require('../database/connection')
module.exports = {
async create(req, resp) {
console.log(req.body)
}
}
The Terminal return undefined, but, I post this
{
"name": "victor",
"email": "victor",
"password": "victor",
"dtnasc": "1999/11/1",
"sexo": "M",
"altura": "1,8",
"peso": "60"
}
I try to use Body-parser too, but it's still the same
PS: sorry for the english
Sounds like you don't have the body-parser middleware set up correctly.
Depending on the version of Express you are using you may have to install it separately.
npm install body-parser --save
If you do have it installed, but still don't find it working make sure to have your express app use the body-parser middleware before you define your routes.
It's a middleware so it will transform the req before passing it along but if you have it after you define your routes it will never be reached.
app.use(bodyParser.urlencoded({extended: true}))
// routes go below
app.get(...)
I make my GET services work in Swagger (with Node.js), but I am not able to make the POST work. Can someone point out where I am making mistake in below testPost service?
my service definition
"/people/testPost": {
"post": {
"summary": "write the test POST.",
"description": "Test",
"operationId": "myService",
"consumes": [
"application/json"
],
"tags": [
"test"
],
"parameters": [
{
"name":"body",
"paramType":"body",
"description": "body for the POST request",
"required":false
}
]
In service (filename = myService.js), I am trying this
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended:true}));
app.post("/people/testPost", function (req, res) {
console.log("I am in the testPost service); //this gets printed
console.log("The req body", req.body) //says 'undefined'
});
Here is my CURL command I use to POST
curl -H "Content-Type: application/json" -X POST -d '{"arg1":"open", "arg2":"IVR","arg3":"", "arg4" :"1234567"}' http://localhost:8016/people/testPost
Any simple POST request that uses Swagger with Node (all I need is how to configure my "body" in the json file) would, hopefully, gets me going
Some one, please, look into my "parameters" and the curl POST and see where I need to make changes/corrections.
because you're receiving JSON request you need an appropriate handler for this. For JSON you should use app.use(bodyParser.json());, see example on module page.
app.use(bodyParser) don't needed btw.