Express res not sending body content - express

I have the most basic express response via res.send() and I can't seem to figure out why it's not returning the body to the client.
Here it is:
app.get('/api/getOrders', (req, res) => {
res.send("hello")
});
It sends a response alright, but it doesn't have a body, it has the status, headers, etc but not the actual message.
Here's the response from the dev tools:
Response {type: 'basic', url: 'http://localhost:9000/api/getOrders?cid=1234564984', redirected: false, status: 200, ok: true, …}
body: (...)
bodyUsed: false
headers: Headers {}
ok:true
redirected:false
status:200
statusText:"OK"
type:"basic"
url:"http://localhost:9000/api/getOrders?cid=1234564984"
[[Prototype]]:Response
Thank you for any help!!

Related

How to send APIKey in Auth header in fetch request in Vue js

I am trying to send post request to a url on which authorization of type API Key is enabled. I am able to send request through the post man. The API is responding perfectly fine, but when I come to fetch in Vuejs. I am unable to send the POST request using fetch.
Screenshot of POSTMAN is attached.
The tried code which I am using in Vuejs is:-
const requestOptions = {
method: "POST",
withCredentials: true,
headers: {
"Content-Type": "application/json",
"X-API-Key":"3C68F15FF89132BF254E5FB648FCA",
},
body: JSON.stringify({
name: this.name,
phonenumber: this.phoneNumber,
msg: this.message,
}),
};
let response = await fetch(
"https://auto.toxiclabs.net/webhook/d6121492-4b9c-4dc2-908f-991001b20b61",
requestOptions
);
The error I am getting
Anyone who can tell me what actually is wrong in my code ?

How to handle the plain/text POST request in the cypress

I have a postman collection and It's POST call and the request body is type of plain/text and I just want to automate this using cy.request but I'm not sure how to pass the test body in the cy.request body section and it returned 400 bad request if I run the below code.
cy.request({
url: `${url}/user`,
method: "POST",
headers: {
'Content-Type': 'plain/text'
},
body: {
"confirmEmail": "true"
}
}).then(res =>{
cy.task('log',"Email id "+res.body.emailAddress);
return res.body;
});
}
The above request return .json response but the input request if text format and the same working fine in the postman tool.
Passing the request body in the below format in the postman tool and its working fine.
confirmEmail=true
My assumption is in the request body our endpoint is expecting a boolean value, but you are passing a string. So changing "confirmEmail": "true" to "confirmEmail": true should work.
cy.request({
url: `${url}/user`,
method: 'POST',
headers: {
'Content-Type': 'plain/text',
},
body: {
confirmEmail: true,
},
}).then((res) => {
cy.log(res.body.emailAddress) //prints email address from response body
})
In case you need to pass parameters in your URL you can directly use qs
cy.request({
url: `${url}/user`,
method: 'POST',
qs: {
confirmEmail: true,
},
headers: {
'Content-Type': 'plain/text',
},
}).then((res) => {
cy.log(res.body.emailAddress) //prints email address from response body
})

How to get a return value from a post request in NextJs 9 Serverless

I'm building a serverless app using NextJs and I'm stuck on how I can get a return value that includes a user's JWT when making a post request to my DB. Everything works as expected but I can't get this one thing down.
In my login page, this is how I handle user-submitted data:
const res = await fetch(`${process.env.BASE_URL}/api/login`, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(userInfo)
})
console.log('successfully logged in')
console.log(res)
In my API, the way I return a value when making a request to /api/login is:
return res.status(201).json({
message: 'Account successfully signed in!',
user,
token
})
Now when I go to check my console.log in dev tools, here's what the response looks like:
type: "basic"
url: "http://localhost:3000/api/login"
redirected: false
status: 200
ok: true
statusText: "OK"
headers: Headers {}
body: ReadableStream
locked: false
__proto__: ReadableStream
bodyUsed: false
__proto__: Response
Nothings there and I don't know why?
This is a fetch body response, you should decode it by the type that you are expecting (in your case json).
const res = await fetch(`${process.env.BASE_URL}/api/login`, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(userInfo)
})
const data = await res.json(); // <--- this is the missing part
console.log('successfully logged in')
console.log(data)

Axios: Network Error and not sending request

I am trying to send a get request with auth headers to api from Vue using axios.
When I try to send it, it gives me a Network Error with no info about it. I have also check network tab and the request is not sending at all.
Before I checked the url using postman and https://www.hurl.it/ and it worked as expected.
Also, I have sent a request to this api using axios to get a token.
Thank you.
const token = "token";
let options = {
method: 'GET',
url: 'http://smev.test-it-studio.ru/api/analytics/PortfolioStructure',
headers: {
'Authorization': `Bearer ${token}`
},
};
axios(options).then((data) => {
console.log(data);
}).catch((error) => {
console.log(error.config);
});
EDIT: Here is the error I get:
Error
columnNumber: 15
config: {…}
adapter: function xhrAdapter()
baseURL: "http://smev.test-it-studio.ru"
data: undefined
headers: Object { Accept: "application/json", Authorization: "Bearer token"}
maxContentLength: -1
method: "GET"
timeout: 0
transformRequest: Object [ transformRequest() ]
transformResponse: Object [ transformResponse() ]
url: "http://smev.test-it-studio.ru/api/analytics/PortfolioStructure"
validateStatus: function validateStatus()
xsrfCookieName: "XSRF-TOKEN"
xsrfHeaderName: "X-XSRF-TOKEN"
__proto__: Object { … }
fileName: "http://uralsib-lk.dev/dist/build.js"
lineNumber: 19074
message: "Network Error"
response: undefined
stack: "createError#http://uralsib-lk.dev/dist/build.js:19074:15\nhandleError#http://uralsib-lk.dev/dist/build.js:18962:14\n"
__proto__: Object { … }
build.js:18589:24
With the help from Soleno, I found out that it was AdBlock what was blocking the request.
I had this problem in rails. It was cors as mentioned above.
The rails server won't show logs so it looks like axios isn't sending the request at all.
Thankfully it's an easy fix.
For rails add this to your gemfile:
gem 'rack-cors'
Then add this to config/initializers/cors.rb
Rails.application.config.middleware.insert_before 0,Rack::Cors do
allow do
origins 'localhost:8080'
resource '*',
headers: :any,
methods: [:get, :post, :put, :patch, :delete, :options, :head]
end
end
Note: Update orgins to the origin of your front end app.

Express CORS response

I am using express to return an api response retrieved via a request call.
router.post('/', function(req, res){
var options = {
...
}
rp(options)
.then(function (parsedBody) {
console.log(parsedBody);
res.json(parsedBody)
})
The console log displays the expected payload, also when I use Postman I also see the expected payload.
When though my client app gets the response it is:
Response {type: "cors", url: "http://localhost:3001/api/", redirected: false, status: 200, ok: true, …}
Ive tried adding CORS middleware:
app.use(function(request, response, next) {
response.header("Access-Control-Allow-Origin", "*");
response.header("Access-Control-Allow-Headers",
"Origin, X-Rquested-With, Content-Type, Accept");
next();
});
My client is a very simple react app using fetch:
fetch('http://localhost:3001/api/', {
method: 'POST',
dataType: 'JSON',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: data,
}).then((response) => {
console.log(response);
}).catch((response) => {
console.log('Error');
});
My react app is localhost:3000 and the express api localhost:3001, the expected payload is a very simple object...
{
athlete: {
firstname: "Matt"
...
}
}
How can I just forward on the api request response to the clients fetch success method?
The problem is not CORS related, the response within the react app needed parsing as json:
.then((response) => {
console.log(response.json());
})