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.
Related
When I use Swagger-codegen 3.x to send the post request and generate a javascript client, I noticed that the javascript client it generated works fine with ESM instead of common JS (require('') syntax). That is, if I want to test the endpoint I have to create a test.mjs file instead of test.js file.
The docker image I used is "swaggerapi/swagger-generator-v3:latest". The endpoint I'm using is "http://localhost:8080/api/generate". I have passed the option useES6 in the body and it does not work.
Here is the body I send the post request. Are there any ways I can create with a common JS?
json: {
"options": {},
"spec": parsedRawdata,
"codegenVersion": "V3",
"lang": "javascript",
"type": "CLIENT"
},
headers: {
"Accept": "application/octet-stream",
"Content-Type": "application/json"
}
I'm proxying requests to an external backend from a Nextjs app and trying to extract an
Authorization header from the response using the native fetch library. However the headers in the fetch response are empty even though they are present in the actual response from the server.
Here's the setup in the next.config.js file:
module.exports = {
async headers() {
return [
{
source: '/api/:path*',
headers: [
{
key: 'Access-Control-Expose-Headers',
value: '*, authorization',
},
],
},
]
},
async rewrites() {
return [
{
source: '/api/:path*',
destination: `${process.env.NEXT_PUBLIC_BASE_URL}/api/:path*`,
},
]
},
}
With my limited knowledge of proxies I'm assuming that it's a reverse proxy and the headers are lost in the response back somewhere inside it.
I've also tried adding a middleware to try to localize where the headers are being lost without any luck.
Does anyone know where I can configure the headers to be included back from the proxy?
Thanks in advance! :)
I am reusing a fetcher from react-native and it seems like the method for extracting headers differs. 😅
This works using fetch in the browser:
response.headers.get('authorization')
In react-native: response.headers.map['authorization']
I am trying to configure a proxy for my API requests using http-proxy-middleware, which the create react app docs suggest. I set up my proxy like this, in the setupProxy.js file:
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function (app) {
app.use(
createProxyMiddleware("/post", {
target: 'https://postman-echo.com',
changeOrigin: true,
logLevel: 'debug'
})
);
};
then, I do a simple POST to an endpoint:
const response = await fetch("/post", {
method: 'POST',
headers: {
'content-type': 'application/json;charset=UTF-8'
},
body: JSON.stringify({ foo1: "bar1", foo2: "bar2" })
});
console.log(await response.json());
According to the http-proxy-middleware docs, I should expect a proxy that does something like this:
[HPM] POST /post -> https://postman-echo.com/post
But instead, the debugger shows this:
[HPM] POST /post -> https://postman-echo.com
The path, /post, does not get appended to the proxy request. The target should actually be https://postman-echo.com/post. My client gets a 404 error because https://postman-echo.com on its own does not match anything on the backend.
If it did reroute correctly, I should expect the same results as a CURL request
curl -X POST -F 'foo1=bar1' -F 'foo2=bar2' https://postman-echo.com/post
{"args":{},"data":{},"files":{},"form":{"foo1":"bar1","foo2":"bar2"},"headers":{"x-forwarded-proto":"https","x-forwarded-port":"443","host":"postman-echo.com","x-amzn-trace-id":"Root=1-61200c54-7b5809be3e78040f09edcd42","content-length":"240","user-agent":"curl/7.64.1","accept":"*/*","content-type":"multipart/form-data; boundary=------------------------bb54b419e41f4a4a"},"json":null,"url":"https://postman-echo.com/post"}%
But I 404 because the path is not added. Why is the path being left out?
I created a simple app that recreates my issue. This looks similar to this issue but they are not the same (I am using the same syntax as the answer suggests).
I got it working. The problem was that I was testing with an endpoint that 404'd. I got confused because the debugger doesn't append /post to the end of the log like the docs say it should.
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
I am trying to make a simple NodeACS app in which I want to receive some data in xml format as request from cURL and in Node ACS app after receiving that data I want to send response to client.
My system configurations are:
Node v0.10.13 (x86)
Titanium SDK version: Titanium Studio, build: 3.4.0.201409261227 Build: jenkins-titanium-rcp-master-197 (origin/master)
OS : Windows 7 64 bit
Following is my code files:
application.js:
function index(req, res) {
console.log(req.headers);
req.on('data', function (data) {
console.log("Data received successfully");
});
req.on('end', function () {
res.writeHead(200);
res.end();
});
}
config.json:
{
"routes":
[
{ "path": "/", "method":"POST", "callback": "application#index" }
],
"filters":
[
{ "path": "/", "callback": "" }
],
"websockets":
[
{ "event": "", "callback": ""}
]
}
I'm running my code from command prompt as:
acs run --port 7788
There are no changes made by me in any other file. The issue is when I'm trying to POST XML data via curl using following command :
curl -X POST -d #output.xml http://localhost:7788/
then only headers is getting printed in console as:
D:\GMON-Server\GMON-Server>acs run --port 7788
ACS: Appcelerator Cloud Services Command-Line Interface, version 1.0.20
Copyright (c) 2012-2014, Appcelerator, Inc. All Rights Reserved.
[INFO] No dependencies detected
[INFO] socket.io started
[INFO] ACS started on port 7788
[INFO] { 'user-agent': 'curl/7.39.0',
host: 'localhost:7788',
accept: '*/*',
'content-length': '55580',
'content-type': 'application/x-www-form-urlencoded',
expect: '100-continue' }
and neither the req.on('data') event nor the req.on('end') event is firing.
Please tell me whether there is any configuration issue or there is something wrong with my code?